SynchronizationContext应用

这个类的应用,官方的说明并不是很多,主要原因是因为微软又出了一些基于SynchronizationContext的类。比如:BackgroundWorker

大家写程序时经常碰到子线程调用UI线程的方法来更新UI。这个时候大家会用到如下办法

private void HandleSomeEvent(object sender, EventArgs e)
{
    if(InvokeRequired)
    {
        BeginInvoke(new EventHandler(HandleSomeEvent), sender, e);
    }
    else
    {
        // Event logic here.
    }
}

但是在我们用到BackgroundWorker的时候,却发现根本不需要再去验证InvokeRequired了,如下代码:

private void AsyncWork_Initialize()
{
    worker = new BackgroundWorker();
    worker.WorkerSupportsCancellation = true;
    worker.DoWork += new DoWorkEventHandler(AsyncWorkDoing);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(AsyncWorkDone);
}

private void AsyncWorkDone(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show(e.Error.Message);
    }
    else if (e.Cancelled)
    {
        MessageBox.Show("数据初始化被取消");
    }
    else
    {
        Object result = e.Result;
        // Event logic here.
    }
}

这因为BackgroundWorker就是用SynchronizationContext的Post方法来回调UI线程的方法的。

这里只是让大家简单了解下SynchronizationContext,至于如何更加灵活的应用它,还需要大家的集思广益。

另外要注意的是:UI线程的SynchronizationContext实际实现类是WindowsFormSynchronizationContext,它重写POST和SEND方法。


posted @ 2013-06-21 10:31  Vester  阅读(301)  评论(0编辑  收藏  举报