Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...