精品文档,仅供学习与交流,如有侵权请联系网站删除
我们在做 winform 应用的时候,大部分情况下都会碰到使用多线程控制界面上
控件信息的问题。然而我们并不能用传统方法来做这个问题,下面我将详细的
介绍。
首先来看传统方法:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thread = new Thread(ThreadFuntion);
thread.IsBackground = true;
thread.Start();
}
private void ThreadFuntion()
{
while (true)
{
this.textBox1.Text =
DateTime.Now.ToString();
Thread.Sleep(1000);
}
}
}
运行这段代码,我们会看到系统抛出一个异常:Cross-thread
operation not valid:Control 'textBox1' accessed from a thread other
than the thread it was created on . 这是因为.net 2.0 以后加强了安全机
制,不允许在 winform 中直接跨线程访问控件的属性。那么怎么解决这个问题
呢,下面提供几种方案。
第一种方案,我们在 Form1_Load()方法中加一句代码:
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls =
false;
Thread thread = new Thread(ThreadFuntion);
thread.IsBackground = true;
【精品文档】第 1 页