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

后端 未结 3 2340
故里飘歌
故里飘歌 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条回答
  • 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.

    0 讨论(0)
  • 2021-02-20 10:17

    If used inconsistently in the logical chain of async calls, ConfigureAwait(false) may add redundant context switches (which usually means redundant thread switches). This may happen in the presence of synchronization context, when some async calls on the logical stack use ConfigureAwait(false) and some don't (more here).

    You still should use ConfigureAwait(false) in your code, but you may want to peek into the 3rd party code you're calling and mitigate any inconsistency with something like this:

    public async Task DoThingAsyc() {
        // do some setup
        await Task.Run(() => otherLib.DoThingAsync()).ConfigureAwait(false);
        // do some other stuff
    }
    

    This would add one extra thread switch, but might potentially prevent many others.

    Moreover, if you're creating a really thin wrapper like you showed, you may want to implement it like below, without async/await at all:

    public Task DoThingAsyc() {
        // do some setup
        return otherLib.DoThingAsync();
    }
    
    0 讨论(0)
  • 2021-02-20 10:23

    Example from http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx

    ... logically you can think of the following code:

    await FooAsync();
    RestOfMethod();
    

    as being similar in nature to this:

    var t = FooAsync();
    var currentContext = SynchronizationContext.Current;
    t.ContinueWith(delegate
    {
        if (currentContext == null)
            RestOfMethod();
        else
            currentContext.Post(delegate { RestOfMethod(); }, null);
    }, TaskScheduler.Current);
    

    which means you should have your context back after the await myLib.DoThingAync(); call.

    0 讨论(0)
提交回复
热议问题