Using async await when implementing a library with both synchronous and asynchronous API for the same functionality

前端 未结 2 405
我在风中等你
我在风中等你 2020-12-14 22:58

I\'ve got a few questions about how to provide both synchronous and asynchronous implementation of the same functionality in a library. I am gonna ask them first and then pr

2条回答
  •  Happy的楠姐
    2020-12-14 23:55

    The general answer here is that making both truly async and sync versions of the same functionality requires 2 different (maybe similar, maybe not) implementations. You can try and find duplicate parts and reuse them using a base class (or a utility class) but the implementations would mostly be different.

    In many cases, people choose to only supply one version of the API, be it asynchronous or not. For example the .Net client library for YouTube API v3 is entirely async all the way through. If you can afford that (many can't) that would be my recommendation.

    About your specific questions:

    1. Not really, other than finding similar parts and abstracting them away.
    2. Not really, synchronous methods need to be tested in a synchronous context while async ones in an async context.
    3. Take 1 (i.e. returning a task directly) is preferable in 2 ways:
      • It lacks the overhead of creating the whole unneeded async state machine which adds a very slight performance boost.
      • ConfigureAwait in this case affects only the code that comes after it, which in this case is none at all. It doesn't affect the caller's code whether it uses ConfigureAwait or not.
    4. Definitely yes (finally, positivity). async code in libraries should use ConfigureAwait(false) by default, and remove it only when there's a specific need to.

提交回复
热议问题