Async Await Reference Implementation

Objective

 
The objective of this document is to identify the common pitfalls and mistakes that occur while implementing, as async/Await is a complex area and even a small mistake or wrong implementation leads to a lot of systems instability issues. The idea is NOT to reinvent the wheel, but instead to capture the best practices and guidelines shared by larger communities.
 
So in case you find any discrepancy or have a better way to do this, please feel free to reach out to discuss it,  and I will update this document as necessary. Moreover it is important for us to get a good hold on the basics and then follow these guidelines with caution. We all as a team need to make sure this document evolves and improves .
 

Areas

  • Use Async/Await for any services. Don’t blindly use it everywhere
  • Suffix Async function with Async - guideline
  • In the main Task function implementation use Task.FromResult() if any return value or Task.CompletedTask() if no return value.
  • Handling cancellation token. One additional parameter and it should be the last; helpful for canceling any task/request.
  • Instead of using .Result, use GetAwaiter().GetResult. This has a big impact on error handling and aggregated errors. Try to avoid this scenario. Due to Synchronization context, it gets into a dead lock situation. 
  • When we don't need the sync context then use ConfigureAwaiter(false)
  • Dont use return from using statement
  • When we use EF then we can’t use in parallel. await.Task.WhenAll or WhenAny. When we use the EF with a database, those are not threadsafe. Use parallelism only when  you have threadsafe e.g. external http call or external service; and it should not be db context. If this is a multiple database then it's okay but if we do it on the same database then it is an issue.

Issue # 1 - Async method is called in a void method

 
InCorrect Usage
  1. public static async Task FooAsync() {  
  2.     // some async code here...    
  3.     await Task.Delay(10000);  
  4. }  
  5. public void ThisWillNotWaitForAsyncCodeToComplete() {  
  6.     try {  
  7.         Console.WriteLine("Before : " + DateTime.Now.ToString());  
  8.         FooAsync();  
  9.         Console.WriteLine("After : " + DateTime.Now.ToString());  
  10.     } catch (Exception ex) {  
  11.         //The below line will never be reached    
  12.         Console.WriteLine(ex.Message);  
  13.     }  
  14. }  
Correct Usage
  1. public static async Task FooAsync() {  
  2.     await Task.Delay(10000);  
  3. }  
  4. public async Task ThisWillNotWaitForAsyncCodeToCompleteAsync() {  
  5.     Console.WriteLine("Before : " + DateTime.Now.ToString());  
  6.     await FooAsync();  
  7.     Console.WriteLine("After : " + DateTime.Now.ToString());  
  8. }  
Changes to be noted carefully,
  1. FooAsync() is called using await.
  2. Method having async Task in the signature
Result
  1. Async / await chain is followed properly.
  2. Parent thread will wait for the child thread to complete. In case of any database or event operations being performed, parent thread will wait for the completion before quitting.
  3. SEVERITY Level = FATAL

Issue # 2 - No “async” keyword used and “task” object is returned

 
InCorrect Usage
  1. public static Task BarAsync() {  
  2.     // some async code here...    
  3.     return Task.Delay(10000);  
  4. }  
  5. public void ThisWillNotWaitForAsyncCodeToComplete() {  
  6.     try {  
  7.         Console.WriteLine("Before : " + DateTime.Now.ToString());  
  8.         BarAsync();  
  9.         Console.WriteLine("After : " + DateTime.Now.ToString());  
  10.     } catch (Exception ex) {  
  11.         //The below line will never be reached    
  12.         Console.WriteLine(ex.Message);  
  13.     }  
  14. }  
Correct Usage
  1. public static async Task BarAsync() {  
  2.     await Task.Delay(10000);  
  3. }  
  4. public async Task ThisWillNotWaitForAsyncCodeToCompleteAsyncAsync() {  
  5.     Console.WriteLine("Before : " + DateTime.Now.ToString());  
  6.     await BarAsync();  
  7.     Console.WriteLine("After : " + DateTime.Now.ToString());  
  8. }  
Changes to be noted carefully,
  1. FooAsync() is using async and not returning task.
  2. ThisWillNotWaitForAsyncCodeToCompleteAsync() is calling FooAsync() using await.
Result
  1. Async / await chain is followed properly.
  2. Parent thread will wait for the child thread to complete. In case of any database or event operations being performed, the parent thread will wait for the completion before quitting.
  3. SEVERITY Level = FATAL

Issue # 3 - Method is marked as “async Task” but no async method is called inside.

 
InCorrect Usage
  1. Public void Foo() {}  
  2. Public void Bar() {}  
  3. public async Task FakeAsyncMethod() {  
  4.     Foo();  
  5.     Bar();  
  6.     Return Task.CompletedTask;  
  7. }  
Correct Usage
  1. Public void Foo() {}  
  2. Public void Bar() {}  
  3. public void FakeAsyncMethod() {  
  4.     Foo();  
  5.     Bar();  
  6. }  
Changes to be noted carefully,
  1. Remove async task from the FakeAsyncMethod()
  2. Removed return task statement.
Result
  1. Normally the sync method should be called as expected.
  2. SEVERITY level = Important

Issue # 4 - async has blocking call instead of using await

 
InCorrect Usage
  1. public static async Task FooAsync() {  
  2.     await Task.Delay(10000);  
  3. }  
  4. public void ThisWillNotWaitForAsyncCodeToCompleteAsync() {  
  5.     Console.WriteLine("Before : " + DateTime.Now.ToString());  
  6.     FooAsync().Result;  
  7.     Console.WriteLine("After : " + DateTime.Now.ToString());  
  8. }  
Correct Usage
  1. public static async Task FooAsync() {  
  2.     await Task.Delay(10000);  
  3. }  
  4. public void ThisWillNotWaitForAsyncCodeToCompleteAsync() {  
  5.     Console.WriteLine("Before : " + DateTime.Now.ToString());  
  6.     await FooAsync();  
  7.     Console.WriteLine("After : " + DateTime.Now.ToString());  
  8. }  
Changes to be noted carefully,
  1. Added await in FooAsync() to follow the appropriate async/await chain.
  2. Using .Result deprives off the async benefit
Result
  • Async method should be called as per the recommendation and the correct way of doing it.
  • SEVERITY level = Important

Issue # 5 - Blocking async method with .Wait

 
InCorrect Usage
  1. public async Task FooAsync(string id) {  
  2.     …  
  3.     some more  
  4.     function code without any await operation inside…  
  5.     await Task.Delay(10000);  
  6. }  
  7. public void Bar() {  
  8.     console.writeline(“Hello world”);  
  9.     FooAsync().Wait();  
  10. }  
Correct Usage
  1. public async Task FooAsync(string id) {  
  2.     …  
  3.     some more  
  4.     function code without any await operation inside…  
  5.     await Task.Delay(10000);  
  6. }  
  7. public async Task BarAsync() {  
  8.     console.writeline(“Hello world”);  
  9.     await FooAsync();  
  10. }  
Changes to be noted carefully,
  1. Use async await in BarAsync() to follow the appropriate async/await pattern.
Result
  • Async method should be called as per the way they are supposed to rather than forcefully converting them to sync and blocking the current thread.
  • SEVERITY level = Important

Issue # 6 - Create task for sync method and wait on the task.

 
InCorrect Usage
  1. public void SomeMethod1() {  
  2.     …  
  3.     some  
  4.     function code….  
  5.     Var task = Task.Run(() => SomeMethod2);  
  6.     task.Wait();…  
  7.     some functional code….  
  8. }  
  9. public void SomeMethod2() {  
  10.     …  
  11.     Some  
  12.     function code goes here...  
  13. }  
Correct Usage
  1. public void SomeMethod1() {  
  2.     …  
  3.     some  
  4.     function code….  
  5.     SomeMethod2();…  
  6.     some functional code….  
  7. }  
  8. public void SomeMethod2() {  
  9.     …  
  10.     Some  
  11.     function code goes here...  
  12. }  
Changes to be noted carefully,
  1. Use sync method normally the way it is supposed to be used. Making a task and then waiting on the task is just wasting an additional thread on the pool when the same work can be done in the main thread itself.
Result
  • Optimized performance rather than bloating CPU for creation of task when method has to be waited on anyway.
  • SEVERITY level = Important

Issue # 7 - Retrieving result of multiple tasks

 
InCorrect Usage
  1. public async Task < string > FooAsync() {  
  2.     string result = string.empty;…  
  3.     some  
  4.     function code…  
  5.     return result;  
  6. }  
  7. public async Task < string > BarAsync() {  
  8.     string result = string.empty;…  
  9.     some  
  10.     function code…  
  11.     return result;  
  12. }  
  1. public void ParentMethod() {  
  2.     var task1 = FooAsync();  
  3.     var task2 = BarAsync();  
  4.     Task.WaitAll(task1, task2);  
Correct Usage
  1. public async Task < string > FooAsync() {  
  2.     string result = string.empty;…  
  3.     some  
  4.     function code…  
  5.     return result;  
  6. }  
  1. public async Task < string > BarAsync() {  
  2.     string result = string.empty;…  
  3.     some  
  4.     function code…  
  5.     return result;  
  6. }  
  7. public async Task ParentMethod() {  
  8.     var task1 = FooAsync();  
  9.     var task2 = BarAsync();  
  10.     await task.WhenAll(task1, task2);  
Changes to be noted carefully,
 
We should avoid mixing blocking & unblocking code. Task.WaitAll is a blocking call whereas Task.WhenAll is nonblocking and maintains the async semantics.
 
Result
  1. Code is optimized and works as per the async / await programming guidelines of avoiding blocking calls.
  2. SEVERITY level = Important

Issue # 8 - Sync version used when Async is available.

 
InCorrect Usage
  1. public bool CheckLabelAlreadyExist(string labelName, Guid facilityKey, int labelTypeCode) {  
  2.     return GetQueryable().Any(x => x.DescriptionText == labelName && x.FacilityKey == facilityKey && x.LabelTypeCode == labelTypeCode);  
  3. }  
CorrectUsage
  1. public async Task < bool > CheckLabelAlreadyExist(string labelName, Guid facilityKey, int labelTypeCode) {  
  2.     return await GetQueryable().AnyAsync(x => x.DescriptionText == labelName && x.FacilityKey == facilityKey && x.LabelTypeCode == labelTypeCode);  
  3. }   
Task Waiting General Rules (phase 1),
 
To Do This …
Instead of This …
Use This
Retrieve the result of a background task
Task.Wait, Task.Result or Task.GetAwaiter.GetResult
await
Wait for any task to complete
Task.WaitAny
await Task.WhenAny
Retrieve the results of multiple tasks
Task.WaitAll
await Task.WhenAll
Wait a period of time
Thread.Sleep
await Task.Delay

Method Naming Conventions,
  1. All async methods should have “async” suffix in the method name for easy readability and differentiation between sync and async methods.
  2. Having “async” in the methods, make it more prominent and reduces the chances of error in implementation.
  3. This can be done in phase 2

Conclusion

 
The async/await is the best for IO bound tasks (networking communication, database communication, http request, etc.) but it is not good to apply on computational bound tasks (traverse on the huge list, render a huge image, etc.). Because it will release the holding thread to the thread pool and CPU/cores available will not be involved to process those tasks. Therefore, we should avoid using Async/Await for computational bound tasks.
 
For dealing with computational bound tasks, I prefer to use Task.Factory.CreateNew with TaskCreationOptions which is LongRunning. It will start a new background thread to process a heavy computational bound task without releasing it back to the thread pool until the task is completed.


Recommended Free Ebook
Similar Articles