.net 2.0中不允许在winform中直接跨线程访问控件,否则会报错.
若在代码中加上Control.CheckForIllegalCrossThreadCalls = false;则不检查跨线程的调用是否合法,不会产生异常.
但常用的方法是使用Invoke 和 BeginInvoke.至于这两者的区别,有待进一步研究.下面通过一个简单的例子看一下如何使用Invoke 解决问题.这是网上常见的例子(作了部分更改).
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
public partial class Form1 : Form
{
private delegate void FlushClient();//代理
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thread = new Thread(CrossThreadFlush);
thread.IsBackground = true;
thread.Start();
}
private void CrossThreadFlush()
{
while (true)
{
Thread.Sleep(1000);
FlushClient fc = new FlushClient(updateTextbox);
this.Invoke(fc);//通过代理调用刷新方法
}
}
private void updateTextbox()
{
this.textBox1.Text = DateTime.Now.ToString();
}
}