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

查看:133
本文介绍了编写一个精心设计的异步/非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

c#5等待/异步模式的API设计

以及其他更接近我的问题。

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 no good and simple way to just make an async or synchronous "wrapper". Stephen Toub has the best info on the subject:


  1. 我是否应该为异步包装器公开同步方法?

  2. 我应该为异步方法公开同步包装?

  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")

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

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