When I received an exception that is related with thread context, I use delegate function and I invoke this delegate function. It is necessary for use control from an other thread. But I've just learned that I can use SynchronizationContext.Post()
function and I can call my delegate in this method.
I'm not sure which one is better? What are differences between these methods?
It is the same thing, SynchronizationContext.Post() calls BeginInvoke() and Send() calls Invoke().
The key property of SynchronizationContext is that there is more than one implementation of it. Important ones are WindowsFormsSynchronizationContext, it uses Control.Begin/Invoke and DispatcherSynchronizationContext, it uses Dispatcher.Begin/Invoke. There are others for ASP.NET, Windows Store (aka WinRT, aka Universal) apps, out-of-process servers that are COM+ hosted, etcetera.
The extra level of indirection helps avoid taking a dependency on the specific method that invokes. Important for any class library of course.
Control.Invoke
is equivalent to SynchronizationContext.Send
in that both are synchronous. Control.BeginInvoke
is equivalent to SynchronizationContext.Post
in that both are asynchronous. Use any of these 4 methods to prevent a cross-thread exception.
Use SynchronizationContext
to encapsulate thread marshaling code. For example, Form1 creates object Worker to do some work on a different thread. The constructor for Worker captures the current (i.e. Form1's) SynchronizationContext
. When Worker produces data to display on Form1, Worker can use the captured SynchronizationContext
to synchronize to Form1's thread before sending a notification, e.g. event, to Form1. This means that Form1 does not need to know about the different thread, does not need to call InvokeRequired
, and has less code. It also means that Worker does not need to know that its client is a Form.
Below is an excellent series explaining SynchronizationContext
:
Understanding SynchronizationContext - Part I
Understanding SynchronizationContext - Part II
Understanding SynchronizationContext - Part III
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With