SynchronizationContext when it flows and when not?

I am trying to learn about SynchronizationContext and friends. If I set a custom synchronization context at the beginning, for example, a console application. Under what conditions will the current synchronization context flow with my asynchronous operations? Are there differences between Task and others, for example. Delegate.BeginInvoke ?

 void Main() { SynchronizationContext.SetSynchronizationContext(new FooContext()); Action a = () => { var current = SynchronizationContext.Current; //current is null here }; a.BeginInvoke(null,null); ...sleep 

If I execute stuff in a thread pool, am I forced to assign a synchronization context to this particular thread that is currently doing my work?

+5
source share
1 answer

Under what conditions will the current synchronization context flow with my asynchronous operations?

When the async method executes await , by default it will grab the current context and use it to resume the async method. This context is SynchronizationContext.Current , if it is not null , in which case it is TaskScheduler.Current . I describe this behavior in my async intro blog post , my MSDN article on SynchronizationContext and my MSDN article on best asynchronization methods .

Are there differences between Task and others, for example. Delegate.BeginInvoke?

This behavior is unique to async and await . Delegate.BeginInvoke means "run this delegate in a thread pool thread", so it does not apply to SynchronizationContext . Also, there are no more modern approaches, such as Task.Run .

If I execute stuff in a thread pool, am I forced to assign a synchronization context to this particular thread that is currently doing my work?

In general, you should not set a synchronization context in a thread that you do not have. If you put it in a thread pool thread, you must delete it before the thread returns to the thread pool. Most likely, if you set up a synchronization context, you just don't need to return a stream (a custom synchronization context is usually associated with a โ€œmain loopโ€ for that stream).

in the above example, the boolean call context thread, but not the synchronization context. any pointers to why this is so would be interesting.

Other contexts are even less documented. Stephen Tuub has a final post on the topic . In fact, some data, such as security, must flow; most other data are not.

+4
source

Source: https://habr.com/ru/post/1208034/


All Articles