最近有个需求要轮询数据库,所以用了timer定时器,然后轮询返回值要在UI有体现,这就exception了,“线程间操作无效: 从不是创建控件的线程访问它”,一查才知道,.net不能直接跨线程访问控件,虽然是安全需要,但还是让人有点小恼火啊。最后用的Invoke解决了这个问题,废话少说上代码:
public delegate void AppendResultTextHandler(string txt, string widgetName);
public void AppendResultText(string txt, string widgetName)
{
AppendResultTextHandler msgCallback = new AppendResultTextHandler2(AppendResultText);
resultTxt.BeginInvoke(new Action(() => {
if (widgetName == "resultTxt")
{
resultTxt.AppendText(txt);//增加文本
resultTxt.ScrollToCaret();//滚动到当前目录
}
else if (widgetName == "count")
{
count.Text = txt;
}
}));
}
最后,在子线程中直接调用AppendResultText方法,over。