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

后端 未结 2 1808
无人共我
无人共我 2020-12-08 20:09

I am still learning the whole Task-concept and TPL. From my current understanding, the SynchronizationContext functions (if present) are used by await to dispat

2条回答
  •  温柔的废话
    2020-12-08 20:25

    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.

提交回复
热议问题