我收到了这个错误:
System.Windows.Forms.dll 中发生类型为“System.InvalidOperationException”的未处理异常
附加信息:跨线程操作无效:控制从创建它的线程以外的线程访问的“Redlight”。
Redlight 和 Greenlight 是图片框。基本上,我希望它能够做的就是每秒在每张图片之间交替。我在这个网站上搜索了类似的错误,我看到它与“调用”有关,但我什至不知道那是什么,有人能指教我吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace EMCTool
{
public partial class EMCTool_MainForm : Form
{
bool offOn = false;
public EMCTool_MainForm()
{
InitializeComponent();
}
private void EMCTool_MainForm_Load(object sender, EventArgs e)
{
System.Threading.Timer timer = new System.Threading.Timer(new System.Threading.TimerCallback(timerCallback), null, 0, 1000);
}
private void timerCallback(object obj)
{
if (offOn == false)
{
Redlight.Show();
offOn = true;
}
else
{
Greenlight.Show();
offOn = false;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当您尝试从未在其上创建的任何线程更新 UI 元素时,您会收到跨线程错误。
Windows 窗体中的控件绑定到特定线程并且不是线程安全的。因此,如果您从不同的线程调用控件的方法,则必须使用控件的调用方法之一将调用编组到正确的线程。此属性可用于确定是否必须调用 invoke 方法,如果您不知道哪个线程拥有控件,这会很有用。
参考这里了解更多
试试这个。这对我来说很好用
if (pictureBoxname.InvokeRequired)
pictureBoxname.Invoke(new MethodInvoker(delegate
{
//access picturebox here
}));
else
{
//access picturebox here
}
Run Code Online (Sandbox Code Playgroud)