3
维护同步和异步版本方法的最佳做法是什么?保持同步和异步执行
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有趣的信息斯蒂芬。有一段时间没有在论坛上看到你。很高兴看到你活跃在SO上。 – 2013-03-19 18:30:21