您的位置:首页 > 编程语言 > C#

C#跨线程调用窗体控件

2010-05-04 14:01 363 查看


在使用多线程可能会碰到跨线程调用 Control的属性与方法,但这时通常会报"Cross-thread operation not valid"的异常,解决方法也简单,可以看下 参考1. 大部分的方法是建立一个delegate,然后判断InvokeRequired并新建一个delegate, 但这种方法比较烦琐,多出了比较多的步骤.

后来google时,找到了参考2. 里面使用了匿名方法,有效的减少了代码量,大家可以看看

private void UpdateUI(string txt, Control ctr){
if(ctr.InvokeRequired){
ctr.BeginInvoke((MethodInvoke)delegate{
UpdateUI(txt,ctr);
});
return;
}
ctr.Text = txt;
}
当然,这样,至少不需要另外去新建一个 delegate了,而且非常直观.

}



reference:
1. C#跨线程调用窗体控件 http://hi.baidu.com/supko/blog/item/67ba6b391bf4f3f9b311c7ce.html
2. MethodInvoker + Anonymous Methods = tEh r0x0r http://www.csharper.net/blog/methodinvoker___anonymous_methods___teh_r0x0r.aspx>http://www.csharper.net/blog/methodinvoker___anonymous_methods___teh_r0x0r.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: