Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid duplicate code with Async

How do you avoid writing the same code twice for an async and a non async method. I am currently using ASP.NET so I am currently on the request thread, and I quickly learned that he below code (that should show my intent), is definetely the wrong way of doing this.

The application deadlocks, as the await keyword tries to get back on the same thread that the .Result is blocking.

The whole reason I am doing this, is to avoid writing the same "FindAll" code twice.

public IEnumerable<Resource> FindAll()
{
   return FindAllAsync().Result;

}

public async Task<IEnumerable<Resource>> FindAllAsync()
{
   return await Context.Resources.ToListAsync();
}

So how do you solve this?

like image 375
André Snede Avatar asked May 29 '14 12:05

André Snede


People also ask

How do you avoid code duplication?

To avoid the problem of duplicated bugs, never reuse code by copying and pasting existing code fragments. Instead, put it in a method if it is not already in one, so that you can call it the second time that you need it.

How do I fix duplicate codes?

Duplicate code is most commonly fixed by moving the code into its own unit (function or module) and calling that unit from all of the places where it was originally used. Using a more open-source style of development, in which components are in centralized locations, may also help with duplication.

Does async await improve performance?

The main benefits of asynchronous programming using async / await include the following: Increase the performance and responsiveness of your application, particularly when you have long-running operations that do not require to block the execution.

Can async method have multiple awaits?

We start a timer, this will allow us to time the code to see how long the code will run for. The solution. In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise.


1 Answers

How do you avoid writing the same code twice for an async and a non async method.

You can't, in the general case.

The operation in question is either naturally asynchronous or naturally synchronous. In this example (a database request), it is naturally asynchronous. So, make the API asynchronous. That is all.

Stephen Toub has a famous pair of blog posts Should I expose synchronous wrappers for asynchronous methods? and Should I expose asynchronous wrappers for synchronous methods? The short answer to both questions is "no."

You can do various hacks to expose both types of APIs (and Stephen covers each approach in his posts), but the benefits are minuscule compared to the drawbacks.

like image 180
Stephen Cleary Avatar answered Sep 21 '22 14:09

Stephen Cleary