2013-03-19 145 views
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; 
} 

但我不確定這個解決方案。有沒有關於這個問題的最佳做法?

回答

4

我們該如何擺脫它?

你不行。

Stephen Toub有一些優秀的博客文章,解釋synchronous wrappers for asynchronous methodsasynchronous wrappers for synchronous methods的缺陷。簡短的回答是:不。

你最好的選擇是保持現在。幾年後,同步方法可以被認爲是過時的。

另請參閱this question

+0

+1有趣的信息斯蒂芬。有一段時間沒有在論壇上看到你。很高興看到你活躍在SO上。 – 2013-03-19 18:30:21