Why was “SwitchTo” removed from Async CTP / Release?

后端 未结 3 1263
傲寒
傲寒 2020-11-29 09:49

I tried to use the SwitchTo method today to switch to the GUI thread, and found that the example I lifted it from does not work, simply because the method is not there.

3条回答
  •  醉梦人生
    2020-11-29 09:54

    It's 2020 and it looks like SwitchTo is set to come back to CLR soon, according to David Fowler and Stephen Toub in this GitHub issue, as there's no more limitations for await inside try/catch.

    IMO, using something like await TaskScheduler.Default.SwitchTo() explicitly is better than relying upon ConfigureAwait(false) in the 3rd party library code, especially if we want to make sure that code doesn't execute on any custom synchronization context. I have a blog post with more details on that, including an experimental implementation of SwitchTo.

    In a nutshell, I believe the first option from the below clearly indicates the intent, with minimum boilerplate code:

    // switch to the thread pool explicitly for the rest of the async method
    await TaskScheduler.Default.SwitchTo();
    await RunOneWorkflowAsync();
    await RunAnotherWorkflowAsync();
    
    // execute RunOneWorkflowAsync on the thread pool 
    // and stay there for the rest of the async method
    await Task.Run(RunOneWorkflowAsync).ConfigureAwait(false);
    await RunAnotherWorkflowAsync();
    
    await Task.Run(async () => 
    {
      // start on the thread pool
      await RunOneWorkflowAsync();
      await RunAnotherWorkflowAsync();
    }).ConfigureAwait(false);
    // continue on the thread pool for the rest of the async method
    
    // start on whatever the current synchronization context is
    await RunOneWorkflowAsync().ConfigureAwait(false);
    // continue on the thread pool for the rest of the async method,
    // unless everything inside `RunOneWorkflowAsync` has completed synchronously
    await RunAnotherWorkflowAsync();
    

提交回复
热议问题