All window objects are associated with the dispatcher where it has been created.
Golden rules:
- Any UI element must be touched from the same UI thread that created it
- Don’t block the UI thread
How to execute slow work then?
In summary,
- perform slow work asynchronously
- update the UI using the Dispatcher.BeginInvoke
Example:
1 2 3 4 5 6 7 8 9 10 |
ThreadStart ts = delegate { DoSlowWork(); Dispatcher.BeginInvoke(DispatcherPriority.Normal, (EventHandler) delegate { DoUIUpdate(); }, null, null); }; ts.BeginInvoke(delegate(IAsyncResult iar) {ts.EndInvoke(iar);}, null ); |
DispatcherPriority list ….
Windows forms way:
1 2 3 4 5 6 7 8 9 10 11 |
SynchronizationContext syncContext = SynchronizationContext.Current; ThreadStart ts = delegate { DoSlowWork(); syncContext.Post(delegate { DoUIUpdate(); }, null); }; ts.BeginInvoke(delegate(IAsyncResult iar) {ts.EndInvoke(iar);}, null ); |