我怎样才能实现两个异步方法及其对应的同步? [英] How can I implement both an async method and its synchronous counterpart?

查看:173
本文介绍了我怎样才能实现两个异步方法及其对应的同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,例如任务<字符串> GetContentAsync(字符串URL)和我的控制台应用程序是没有准备好采取第三方物流的优势在内部,但在以后的日子也许这将是。

I have a method such as Task<string> GetContentAsync(string url) and my console application is not quite ready to take advantage of the TPL internally, but maybe at a later date it will be.

我怎么能轻松地为这个(或其他)的方法写一个同步封装(不可替代的实现)?

How can I easily write a synchronous wrapper (not an alternative implementation) for this (or other) methods?

推荐答案

如果您的图书馆需要实现同步和异步的成员,那么你实现这两个成员。有没有捷径可走(假设这是打算成为一个可重用库)。

If your library needs to implement both synchronous and asynchronous members, then you implement both members. There are no shortcuts (assuming this is intended to be a reusable library).

public async Task<string> GetContentAsync(string url)
{
  ... // Logic here, e.g., using HttpClient
}

public string GetContent(string url)
{
  ... // Duplicate logic here, e.g., using WebClient
}

逻辑的重复肯定是不幸的,但如果你试图走捷径,你会真正最终在一个糟糕的情况。的范围为什么是有点长了一个SO回答,但斯蒂芬Toub覆盖在他的经典对博客文章的"Should揭露同步封装为异步方法?和的"Should揭露异步包装器同步的方法?

顺便说一句,回答这两个问题是没有。另请参见我这样,请回答这里

BTW, the answer to both questions is "no". Also see my SO answer here.

这篇关于我怎样才能实现两个异步方法及其对应的同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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