在用C#写PC上位机的时候,难免会用到多线程,多出的线程又难免会用到主现程的UI控件,但是,UI是不能直接跨线程使用的。
在WinForm中,我们要跨线程访问窗口控件,只需要设置属性CheckForIllegalCrossThreadCalls = false;即可。
在WPF中要麻烦一下,在WPF中的窗口控件都有一个Dispatcher属性,允许访问控件的线程;既然不允许直接访问,就告诉控件我们要干什么就好了。
加入以下一段代码:
private delegate void outputDelegate(string msg);
private void output(string msg)
{
this.DisplayTextBox.Dispatcher.Invoke(new outputDelegate(outputAction), msg);
}
private void outputAction(string msg)
{
this.DisplayTextBox.AppendText(msg);
this.DisplayTextBox.AppendText(" \n ");
}
调用的代码这样写:
上面代码用到了委托,委托实际就相当于C语言中的回调函数的作用。