Avoid duplicate code with Async
.net, asp.net-mvc, async-await, c#
Solution
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.
Problem
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?