Can ConfigureAwait(false) in a library lose the synchronization context for the calling application?

后端 未结 3 2288
故里飘歌
故里飘歌 2021-02-20 09:54

I\'ve read the advice many times from people smarter than me, and it has few caveats: Always use ConfigureAwait(false) inside library code. So I\'m

3条回答
  •  不要未来只要你来
    2021-02-20 09:59

    No.

    The capturing of the SynchronizationContext happens on await. ConfigureAwait configures the specific await.

    If the application calls a library's async method and awaits it the SC is captured on the spot regardless of what happens inside the call.

    Now, because the async method's synchronous part (which is the part before the first await) is executed before a task is returned to be awaited, you can mess around with the SynchronizationContext there, but ConfigureAwait doesn't do that.


    In your specific example you seem to be returning the result of ConfigureAwait from the async method. That can't happen because ConfigureAwait returns the ConfiguredTaskAwaitable struct. If however we change the method return type:

    public ConfiguredTaskAwaitable DoThingAsyc() 
    {
        return otherLib.DoThingAsync().ConfigureAwait(false);
    }
    

    Then awaiting it will indeed affect the calling code's await behavior.

提交回复
热议问题