C# 维护同步和异步实现
维护方法的同步和异步版本的最佳实践是什么C# 维护同步和异步实现,c#,.net,async-await,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 parsedDa
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
}
但我不确定这个解决方案。关于这个问题有什么最佳实践吗
我们怎样才能摆脱它
你不能
斯蒂芬·图布(Stephen Toub)有一些优秀的博客文章解释了和的缺陷。简单的回答是:不要
你最好的办法是暂时保持这两种状态。几年后,可以认为同步方法已经过时
另请参见。+1有趣的信息Stephen。好久没在论坛上见到你了。很高兴看到你如此活跃。
public ImportData Import(ZipFile zipFile)
{
var importAsyncTask = ImportAsync(zipFile);
importAsyncTask.Wait();
return importAsyncTask.Result;
}