避免线程切换时的BeginInvoke之舞

何谓BeginInvoke之舞.

delegate void MyHandlerDelegate();
void MyHandler()
{
// "The BeginInvoke dance"
if (this.InvokeRequired){
BeginInvoke(
new MyHandlerDelegate(MyHandler) );
return;
}
do GUI stuff
}

在做多线程的程序时,我们常常在经过大量计算后,要将结果反馈给UI.如果在多线程时,直接给UI的更新的话,会引发异常.相信大家都遇上过这样的问题,同时解决的方案就是上面的所谓BeginInvoke之舞.

在2.0里提供了AsyncOperationManager.支持异步方法调用的类提供并发管理.利用他就可以避免BeginInvoke了.再说每次写那样个东东也很烦.

public partial class Form1 : Form
{
AsyncOperation asyncOperation ;
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
asyncOperation = AsyncOperationManager.CreateOperation(null);
Thread t = new Thread(new ThreadStart(RunTask));
t.Start();
}

public void RunTask()
{
Thread.Sleep(5000);
asyncOperation.Post(new SendOrPostCallback(ShowText), "hello");
}

void ShowText(object s)
{
this.textBox1.Text = s.ToString();
}
}

你可能感兴趣的:(thread,多线程,UI)