我怎样才能实现两个异步方法及其对应的同步?两个、方法

2023-09-07 08:51:10 作者:饿默然、悲伤

我有一个方法,例如任务<字符串> 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覆盖在他的经典对博客文章的