保持同步和异步实现 [英] Maintain both synchronous and asynchronous implementations
问题描述
什么是维护方法的同步和异步版本的最佳做法?
让我们假设我们有以下的方法:
公共ImportData导入(ZipFile的压缩文件)
{
... //第1步:初始化
变种extractedZipContent = zipFile.Extract(); //第2步
... //步骤3.一些中间的东西
VAR parsedData = ParseExtractedZipContent(extractedZipContent); //第4步
... //步骤5.有些code算账
}
步骤2和4长期运行的,所以我们要异步调用它们导入方法的异步版本:
公共异步任务< ImportData> ImportAsync(ZipFile的压缩文件)
{
... //第1步:初始化
VAR extractedZipContent =等待zipFile.Extract(); //第2步
... //步骤3.一些中间的东西
VAR parsedData =等待ParseExtractedZipContentAsync(extractedZipContent); //第4步
... //步骤5.有些code算账
}
现在我们有同步和异步实现。但我们也有code重复。我们怎样才能摆脱它?
我们可以提取步骤1,3和5以及从两个实现调用它们。但1.我们还是重复的方法调用顺序2.它不是真实code
那么容易我来最好的办法是有异步实现。和同步实施将只是等待异步执行完毕:
公共ImportData导入(ZipFile的压缩文件)
{
VAR importAsyncTask = ImportAsync(zip文件);
importAsyncTask.Wait();
返回importAsyncTask.Result;
}
不过,我不知道该解决方案。是否有关于这个问题的任何bestpractices?
如何才能摆脱它?
您不能。
斯蒂芬Toub有一些优秀的博客文章解释的同步封装器和异步包装异步方法同步方法的。简短的回答是:不要
您最好的办法是既保持现在。从现在开始同步方法几年可以被认为是过时的。
另请参见这个问题。
What are the best practices to maintain both synchronous and asynchronous versions of the method?
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
}
Step 2 and 4 a long-running so we want to call them asynchronously in asynchronous version of Import method:
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
}
Now we have both synchronous and asynchronous implementations. But we also have code duplication. How can we get rid of it?
We can extract Step 1, 3 and 5 and call them from both implementations. But 1. we still duplicate the order of methods calls 2. it is not so easy on real code
The best idea I came to is to have asynchronous implementation. And synchronous implementation would just wait for asynchronous implementation is finished:
public ImportData Import(ZipFile zipFile)
{
var importAsyncTask = ImportAsync(zipFile);
importAsyncTask.Wait();
return importAsyncTask.Result;
}
But I am not sure about this solution. Are there any bestpractices regarding this problem?
How can we get rid of it?
You can't.
Stephen Toub has some excellent blog posts explaining the pitfalls of synchronous wrappers for asynchronous methods and asynchronous wrappers for synchronous methods. The short answer is: don't.
Your best bet is to maintain both for now. A few years from now the synchronous methods can be considered obsolete.
Also see this question.
这篇关于保持同步和异步实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!