Windows Form线程同步

.Net多线程开发中,经常需要启动工作线程Worker thread处理某些事情,而工作线程中又需要更新主线程UI thread的界面状态。我们只能在主线程中操作界面控件,否则.Net会抛出异常。
那么如何才能在Worker thread中将界面更新操作同步到主线程中去完成呢?【How synchonize the UI update task back to UI thread from a worker thread?】
Windows Form中经典的办法是在UI Update function中调用control.InvokeRequired方法判断是否需要同步,如果需要,则调用control.Invoke或control.BeginInvoke实现同步。
Invoke方法是阻塞式的[Blocking],类似于Win32 API SendMessage,而BeginInvoke方法是非阻塞的【NonBlocking,fire and forget】,类似于Win32 API PostMessage.
Windows Form中还实现了一个类SynchronizationContext,调用SynchronizationContext.Send()/Post()也可以更简单地实现线程间的阻塞式/非阻塞式同步,in fact SynchronizationContext.Post() calls BeginInvoke() and Send() calls Invoke().
关于线程同步,一个有趣的问题是,界面更新方法中产生的异常到底会被主线程还是工作线程捕获呢?答案是It dedends on which synchronization mode is used. 如果使用阻塞式Invoke()/Send()同步函数,工作线程会捕捉到异常;而如果使用非阻塞式BeginInvoke()/Post()同步函数,异常则会在主线程中被捕获。
Codeproject中有一个系列文章把SynchronizationContext讲透透,这里直接链接:
系列I

原文地址:https://www.cnblogs.com/egoechog/p/6391080.html