Write a well designed async / non-async API

前端 未结 3 898
深忆病人
深忆病人 2020-11-27 03:39

I\'m facing the problem of designing methods that with performs network I/O (for a reusable library). I\'ve read this question

c# 5 await/async pattern in API design

3条回答
  •  情书的邮戳
    2020-11-27 04:12

    If you want the most maintainable option, only provide an async API, which is implemented without making any blocking calls or using any thread pool threads.

    If you really want to have both async and synchronous APIs, then you'll encounter a maintainability problem. You really need to implement it twice: once async and once synchronous. Both of those methods will look nearly identical so the initial implementation is easy, but you will end up with two separate nearly-identical methods so maintenance is problematic.

    In particular, there's a no good and simple way to just make an async or synchronous "wrapper". Stephen Toub has the best info on the subject:

    1. Should I expose asynchronous wrappers for synchronous methods?
    2. Should I expose synchronous wrappers for asynchronous methods?

    (the short answer to both questions is "no")

提交回复
热议问题