维护同步和异步实现

4

如何维护同步和异步版本的方法的最佳实践?

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步都是长时间运行的,因此我们希望在导入方法的异步版本中异步调用它们:

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个回答

5

+1 有趣的信息 Stephen。很久没在论坛上见到你了。很高兴看到你在 Stack Overflow 上积极活跃。 - P.Brian.Mackey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接