这几天,碰到一个通过SerialPort口触发UI控件引发的UI控件跨线程调用的问题,查了大半天,基本有三类解问决方案
1.修改Control.CheckForIllegalCrossThreadCalls 这个属性,变True为False,来关闭出错报警。
2.用BackgroundWorker方法,也可以。
3.用Invoke和InvokeRequired方法来写。
用第一个方法写,试下来发现在调用GridView是会出现红叉叉的问题,查了一下是线程报警,其他控件正常。
第二方法太复杂。
第三个方法,在codeproject上查到一个好简单的方法,记下来分享一下
分有参数写法和无参数写法
1.有参数写法
public void WithParameterMethod(int parameter)
{
if (InvokeRequired)
{
Invoke(new MethodInvoker( delegate { // Call your method again WithParameterMethod(parameter); } ));
}
else { // Do your thing here! }
}
2.无法参数写法
public void NoParameterMethod()
{
if (InvokeRequired)
{
Invoke(new MethodInvoker( // Call your method again NoParameterMethod ));
}
else { // Do your thing here! }
}
方便吧,试一下!