我现在正在编写GUI应用程序一段时间,我总是使用一个方法是使用MethodInvoker + lambda函数来进行跨线程访问.
从示例中我发现我总是看到这样的东西:
版本1
if (InvokeRequired)
{
Invoke(new MethodInvoker(() =>
{
Label1.Text = "Foobar";
});
}
else
{
Label1.Text = "Foobar";
}
Run Code Online (Sandbox Code Playgroud)
然而,这会导致代码重复 - >对我来说是主要的坏人.
那有什么不对呢?
版本2
MethodInvoker updateText = new MethodInvoker(() =>
{
Label1.Text = "Foobar";
});
if (InvokeRequired)
{
Invoke(updateText);
}
else
{
updateText();
}
Run Code Online (Sandbox Code Playgroud)
现在我将功能捆绑在一个变量中,并在适当时使用Invoke或函数指针调用它.版本2的性能更差吗?或者我使用匿名函数是不好的做法?
我收到了这个错误:
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 …Run Code Online (Sandbox Code Playgroud)