我們在做winform應用的時候
首先來看傳統方法
public partial class Form
{
public Form
{
InitializeComponent();
}
private void Form
{
Thread thread = new Thread(ThreadFuntion);
thread
thread
}
private void ThreadFuntion()
{
while (true)
{
this
Thread
}
}
}
運行這段代碼
第一種方案
private void Form
{
Control
Thread thread = new Thread(ThreadFuntion);
thread
thread
}
加入這句代碼以後發現程序可以正常運行了
下面來看第二種方案
public partial class Form
{
private delegate void FlushClient();//代理
public Form
{
InitializeComponent();
}
private void Form
{
Thread thread = new Thread(CrossThreadFlush);
thread
thread
}
private void CrossThreadFlush()
{
//將代理綁定到方法
FlushClient fc = new FlushClient(ThreadFuntion);
this
}
private void ThreadFuntion()
{
while (true)
{
this
Thread
}
}
}
使用這種方式我們可以看到跨線程訪問的異常沒有了
其實不然
現在來讓我們看看推薦的解決方案
public partial class Form
{
private delegate void FlushClient();//代理
public Form
{
InitializeComponent();
}
private void Form
{
Thread thread = new Thread(CrossThreadFlush);
thread
thread
}
private void CrossThreadFlush()
{
while (true)
{
//將sleep和無限循環放在等待異步的外面
Thread
ThreadFunction();
}
}
private void ThreadFunction()
{
if (this
{
FlushClient fc = new FlushClient(ThreadFunction);
this
}
else
{
this
}
}
}
運行上述代碼
From:http://tw.wingwit.com/Article/program/net/201311/11832.html