跨线程访问控件
时间:2010-08-31 来源:iceknp
跨线程访问控件,定义一个委托,委托指向的是该方法,然后使用Invoke方法调用这个委托。
代码private Thread thdSample;
private void btnReceive_Click(object sender, EventArgs e)
{
thdSample = new Thread(new ThreadStart(thdSampleRun));
thdSample.Start();
}
public void thdSampleRun()
{
SetReceiveText();
}
public delegate void SetReceiveTextEventHandler();
public void SetReceiveText()
{
if (this.InvokeRequired)
{
SetReceiveTextEventHandler handler =
new SetReceiveTextEventHandler(SetReceiveText);
this.Invoke(handler, new object[] { });
}
else
{
lock (rtbReceive)
{
rtbReceive.AppendText("跨线程调用主线程控件...");
rtbReceive.AppendText("\n");
}
thdSample.Abort();
}
}
lock期间:
1.其他线程无法访问rtbReceive控件。
2. 其他线程无法执行lock里面代码块。
若有疑问或不正之处,欢迎提出指正和讨论。
相关阅读 更多 +