C#用副线程去试图修改主线程的UI控件会报出异常,解决方案是使用副线程注册事件通知主线程自己去修改UI控件
在winform中,方法如下
private void button1_Click(object sender, EventArgs e)
{
Thread myThread = new Thread (new ThreadStart(fun));
myThread.Start();
} private void fun()
{
textBox1.BeginInvoke(new Action(()=>{textBox1.Text="hello";}));
}
在WPF中,方法如下
private void button1_Click(object sender, EventArgs e)
{
Thread myThread = new Thread (new ThreadStart(fun));
myThread.Start();
} private void fun()
{
TextBox1.Dispatcher.BeginInvoke(new Action(()=>{TextBox1.AppendText("hello");}));
}