ConfigureAwait(false) vs setting sync context to null

后端 未结 2 1539
傲寒
傲寒 2021-02-08 05:07

I often see recommended for async library code, that we should use ConfigureAwait(false) on all async calls to avoid situations where the return of our call will be

2条回答
  •  孤独总比滥情好
    2021-02-08 05:55

    Synchronization Context is similar to static variable and changing it without restoring before control leaves your method will lead to unexpected behavior.

    I don't believe you can safely set current thread's synchronization context inside library function that await anything as restoring context in the middle of compiler generated code is not really possible to my knowledge.

    Sample:

     async Task MyLibraryMethodAsync()
     {
        SynchronizationContext.SetSynchronizationContext(....);
        await SomeInnerMethod(); // note that method returns at this point
    
        // maybe restore synchronization context here...
        return 42;
     }
    
     ...
     // code that uses library, runs on UI thread
    
     void async OnButtonClick(...)
     {
        // <-- context here is UI-context, code running on UI thread
        Task doSomething = MyLibraryMethodAsync(); 
        // <-- context here is set by MyLibraryMethod - i.e. null, code running on UI thread
        var textFromFastService = await FastAsync();
        // <-- context here is set by MyLibraryMethod, code running on pool thread (non-UI)
        textBox7.Text = textFromFastService; // fails...
    
        var get42 = await doSomething;
    }
    

提交回复
热议问题