简体   繁体   中英

Maintain both synchronous and asynchronous implementations

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM