Is it advantageous to use ConfigureAwait(false) in a library that directly returns a Task from a call to another library?

后端 未结 2 1380
[愿得一人]
[愿得一人] 2021-02-15 19:35

Follow-up to this question. I have a library with many async methods that thinly wrap HttpClient. Effectively they just do some setup and directly return the Task r

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-15 20:02

    No, don't do this.

    Since you're not using await, you're not supposed to configure for it in advance. It's the responsibility of the caller of your library to do the ConfigureAwait call. And the caller may well want to call ConfigureAwait(true) instead of ConfigureAwait(false) - you don't know that.

    Calling ConfigureAwait(false) in library code is best practice only when you await on it in the library.

    In most cases, code like this:

    async Task DoSomethingAsync()
    {
        return await DoSomethingElseAsync().ConfigureAwait(false);
    }
    

    Is equivalent to:

    Task DoSomethingAsync()
    {
        return DoSomethingElseAsync();
    }
    

    if DoSomethingElseAsync respects the Task contract (for instance, if it returns a failed Task instead of throwing exceptions).

    Creating an additional state machine for that is just adding one layer of wrapping code with no added value - it is better to simply return the Task directly.

    In other words: you get no efficiency benefit whatsoever from doing this, quite the contrary.

提交回复
热议问题