保持同步和异步实现

时间:2013-03-19 18:24:31

标签: c# .net async-await

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

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;
}

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

1 个答案:

答案 0 :(得分:5)

  

我们怎样摆脱它?

你不能。

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

你最好的选择是现在保持两者。几年后,同步方法可以被认为是过时的。

另见this question

相关问题