noseratio
noseratio

Reputation: 61736

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?

Upvotes: 9

Views: 699

Answers (1)

Hans Passant
Hans Passant

Reputation: 942256

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.

Upvotes: 12

Related Questions