The following is a typical implementation of SynchronizationContext.CreateCopy
:
public class CustomSynchronizationContext : SynchronizationContext
{
// ...
public override SynchronizationContext CreateCopy()
{
return this;
}
}
The MSDN docs are scarce about this method. My questions are:
SynchronizationContext is a representation of the current environment that our code is running in. That is, in an asynchronous program, when we delegate a unit of work to another thread, we capture the current environment and store it in an instance of SynchronizationContext and place it on Task object.
It gets called by ExecutionContext.Capture(). A rather important method, it sets up the Thread.ExecutionContext property. And is used to ensure that a thread that is started will use the same synchronization provider as the original thread that started the worker thread. It makes sure that a call marshaled by Post or Send goes back to the correct thread.
Whether you need a copy or not depends on what you expect to happen when the original synchronization provider ends its lifetime. There certainly isn't any need for a copy of SynchronizationContext, its Post/Send methods don't actually do any useful marshaling at all, Post just runs the target on a threadpool thread, Send just executes the target immediately. So just returning this is good enough.
It does matter on a real provider, like WindowsFormsSynchronizationContext(marshals with Control.Begin/Invoke) or DispatcherSynchronizationContext (marshals with Dispatcher.Begin/Invoke). When the UI thread of a Winforms or WPF app ends and a worker thread is still executing and making invoke calls then you want a get a good diagnostic. Which requires keeping a reference on the original Control or Dispatcher so it can throw a decent exception, like InvalidOperationException or ObjectDisposedException. The copy adds the reference.
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