有以下四种方式
一、通过设置窗体属性,取消线程安全检查,来避免“线程间操作无效异常”
public Form1()
{
CheckForIllegalCrossThreadCalls = false;//取消线程安全检查
}
顾名思义,取消线程安全检查,在复杂的调用下有一定的危险性 。
二、通过BackgroudWorker取代Thread执行异步操作
三、通过UI控件的Invoke/BeginInvoke方法更新
1.Winform版
文中Invoke()的两个参数含义如下
delegado 指的是调用控件的函数的委托
parametros 指的是调用控件函数的参数组,没有参数可以是null
if (this.InvokeRequired)
{
this.Invoke(delegado, parametros);
}
2.WPF
WPF程序中无法直接调用InvokeRequired和Invoke,但有对应的替代,如下。
if (!this.Dispatcher.CheckAccess())
{
this.Dispatcher.Invoke(new Action(() =>
{
Send();//调用控件的函数
}));
}