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

可紊 提交于 2019-11-28 23:45:16

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.

Generally speaking, APIs should be either asynchronous or synchronous. E.g., if your implementation includes I/O, it should be asynchronous.

That said, there are scenarios where you do want to have both synchronous and asynchronous APIs. E.g., if the work is naturally asynchronous, but the synchronous APIs need to be kept for backwards compatibility.

If you're in that situation, I recommend using the boolean argument hack to minimize the amount of duplicated code. Asynchronous wrappers over synchronous methods and synchronous wrappers over asynchronous methods are both antipatterns.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!