写一个精心设计的异步/非异步API [英] Write a well designed async / non-async 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
和还其他的更接近我的问题。
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.
推荐答案
如果你最想要的维护选项,只提供一个异步
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.
如果你真的想兼得异步
和同步的API,那么你会遇到可维护性问题。你真的需要实现它两次:一次异步
和一次同步。这两种这些方法看起来几乎相同所以最初的实施是容易的,但你最终将两个单独的几乎相同的方法,所以维修是有问题的。
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.
在特定的,有只使一个异步
或同步包装没有很好的和简单的方法。斯蒂芬Toub有关于这个问题的最好方式:
In particular, there's no good and simple way to just make an async
or synchronous "wrapper". Stephen Toub has the best info on the subject:
- Should I expose asynchronous wrappers for synchronous methods?
- Should I expose synchronous wrappers for asynchronous methods?
(简短的回答这两个问题是否)
(the short answer to both questions is "no")
这篇关于写一个精心设计的异步/非异步API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!