How to get a Task that uses SynchronizationContext? And how are SynchronizationContext used anyway?

Imi picture Imi · Jun 4, 2013 · Viewed 28.3k times · Source

I am still learning the whole Task-concept and TPL. From my current understanding, the SynchronizationContext functions (if present) are used by await to dispatch the Task "somewhere". On the other hand, the functions in the Task class do not use the context, right?

So for example Task.Run(...) will always dispatch the action on an worker thread of the thread pool and ignore the SynchronizationContext.Current completely. await Foobar() would use the context to execute the generated task after the await?

If that is true, my question is: How can I obtain a Task, that actually runs an action but is dispatched using SynchronizationContext.Current.Send/Post ?

And can anyone recommend a good introduction into SynchronizationContext, especially when and how they are used by the rest of the framework? The MSDN seems to be very quiet about the class. The top Google hits (here and here) seem to be tailored to Windows Forms dispatching only. Stephen Cleary wrote an article which is nice to learn what contexts already exist and how they work, but I lack understanding of where and when they are actually used.

Answer

Dennis picture Dennis · Jun 4, 2013

How can I obtain a Task, that actually runs an action but is dispatched using SynchronizationContext.Current.Send/Post?

Use special task scheduler:

Task.Factory.StartNew(
    () => {}, // this will use current synchronization context
    CancellationToken.None, 
    TaskCreationOptions.None, 
    TaskScheduler.FromCurrentSynchronizationContext());

And can anyone recommend a good introduction into SynchronizationContext

Look at the article It's All About the SynchronizationContext by Stephen Cleary.