Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The purpose of SynchronizationContext.CreateCopy

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:

  1. Under what circumstances does it get called by the Framework?
  2. When to implement the actual copy logic, rather than just returning a reference to the source instance?
like image 569
noseratio Avatar asked Jan 11 '14 12:01

noseratio


People also ask

What is SynchronizationContext?

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.


1 Answers

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.

like image 57
Hans Passant Avatar answered Nov 13 '22 08:11

Hans Passant