编写一个设计良好的异步/非异步 API [英] Write a well designed async / non-async API

查看:30
本文介绍了编写一个设计良好的异步/非异步 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临设计执行网络 I/O(用于可重用库)的方法的问题.我已经阅读了这个问题

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

API 设计中的 c#5 await/async 模式

还有其他更接近我的问题.

and also other ones closer to my issue.

那么,问题是,如果我想提供异步和非异步方法,我必须如何设计这些方法?

So, the question is, if I want provide both async and non-async method how I've to design these?

例如要公开一个方法的非异步版本,我需要做类似的事情

For example to expose a non-async version of a method, I need to do something like

public void DoSomething() {
  DoSomethingAsync(CancellationToken.None).Wait();
}

我觉得这不是一个很棒的设计.我想要一个建议(例如)关于如何定义可以包装在公共方法中以提供两个版本的私有方法.

and I feel it's not a great design. I'd like a suggestion (for example) on how to define private methods that can be wrapped in public ones to provide both versions.

推荐答案

如果你想要最可维护的选项,只提供一个 async API,它的实现不进行任何阻塞调用或使用任何线程池线程.

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.

如果您真的想要同时拥有 async 和同步 API,那么您会遇到可维护性问题.你真的需要实现它两次:一次 async 和一次同步.这两种方法看起来几乎相同,因此最初的实现很容易,但最终会得到两个几乎相同的独立方法,因此维护是有问题的.

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.

特别是,没有一种好的和简单的方法来制作 async 或同步包装器".Stephen Toub 拥有关于该主题的最佳信息:

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. 我应该为同步公开异步包装器吗?方法?
  2. 我是否应该为异步公开同步包装器方法?

(对这两个问题的简短回答都是否")

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

但是,如果您想避免重复实现,可以使用一些技巧;最好的通常是 布尔参数破解.

However, there are some hacks you can use if you want to avoid the duplicated implementation; the best one is usually the boolean argument hack.

这篇关于编写一个设计良好的异步/非异步 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆