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

后端 未结 3 2339
故里飘歌
故里飘歌 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 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();
    }
    

提交回复
热议问题