原文链接:https://blog.youkuaiyun.com/liyazhen2011/article/details/87928952"
写了一个不断生成随机数的程序,姑且可以看做是简易版的抽奖程序,抛出了了“线程间操作无效: 从不是创建控件的线程访问它”的错误。先看一下代码:
using System;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApp4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
new Thread(()=> {
Random random = new Random();
while (true)
{
label1.Text = random.Next(1, 10).ToString();
}
}).Start();
}
}
}
出现上述错误的原因是:.NET禁止了跨线程调用控件。只有创建界面的主线程才能访问界面上的控件label1,新创建的线程不能访问。有两种方法解决该问题:
1.忽略对跨线程调用的检测
在窗体构造函数中设置Control.CheckForIllegalCrossThreadCalls =false。
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
2.使用委托
控件是在与调用线程不同的线程上创建的,可以通过 Invoke 方法对控件进行调用。
using System;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApp4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
new Thread(()=> {
Random random = new Random();
while (true)
{
Action action = () =>
{
label1.Text = random.Next(1, 10).ToString();
};
Invoke(action);
}
}).Start();
}
}
}