【问题标题】:Maintain both synchronous and asynchronous implementations维护同步和异步实现
【发布时间】:2013-03-19 18:24:30
【问题描述】:

维护该方法的同步和异步版本的最佳做法是什么?

Let's suppose we have the following method:
public ImportData Import(ZipFile zipFile)
{
  ... //Step 1. Initialization
  var extractedZipContent = zipFile.Extract(); //Step 2
  ... //Step 3. Some intermediate stuff
  var parsedData = ParseExtractedZipContent(extractedZipContent); //Step 4
  ... //Step 5. Some code afterwards
}

第 2 步和第 4 步需要长时间运行,因此我们希望在 Import 方法的异步版本中异步调用它们:

public async Task<ImportData> ImportAsync(ZipFile zipFile)
{
  ... //Step 1. Initialization
  var extractedZipContent = await zipFile.Extract(); //Step 2
  ... //Step 3. Some intermediate stuff
  var parsedData = await ParseExtractedZipContentAsync(extractedZipContent); //Step 4
  ... //Step 5. Some code afterwards
}

现在我们有同步和异步实现。但是我们也有代码重复。我们怎样才能摆脱它?

我们可以提取步骤 1、3 和 5 并从两个实现中调用它们。但是 1. 我们仍然重复方法调用的顺序 2. 在实际代码中并不那么容易

我想到的最好的想法是异步实现。而同步实现只会等待异步实现完成:

public ImportData Import(ZipFile zipFile)
{
  var importAsyncTask = ImportAsync(zipFile);
  importAsyncTask.Wait();
  return importAsyncTask.Result;
}

但我不确定这个解决方案。有没有关于这个问题的最佳实践?

【问题讨论】:

    标签: c# .net async-await


    【解决方案1】:

    我们怎样才能摆脱它?

    你不能。

    Stephen Toub 有一些出色的博客文章解释了 synchronous wrappers for asynchronous methodsasynchronous wrappers for synchronous methods 的缺陷。简短的回答是:不要。

    您最好的选择是暂时保持两者。几年后,同步方法可能会过时。

    另见this question

    【讨论】:

    • +1 有趣的信息斯蒂芬。好久没在论坛看到你了。很高兴看到您积极参与 SO。
    最近更新 更多