TechBubbles Microsoft Technology BLOG

Async / Await guide-lines

There are lot of different ways to use Async\await in C#. It is bit difficult to understand what different methods, fields and keywords are under tasks and how they are different? This post outlines some bad examples that developer shouldn’t use and explains the alternate solution.

Bad example1: This locks up the UI. Never use .Result

Above line is wrapper method on taskservice which returns task of string. Familiar use case would be, if you are using http client and want to get string asynchronously then you use task.run and wait for the result. The whole idea about task and waiting on it is long running process , example you are calling an API from UI and you dont want to block the UI until you get the response from API.

What’s wrong in the code ?

You are invoking the method with result! stop calling it, it basically making your asynchronous method running synchronous!!!

What is the fix?

so remove the result from method and add await to the line.

Bad example2: Awaiting tasks in a for loop causes the tasks to be awaited synchronously (one after another)

For example, you have five REST endpoints that needs to be called asynchronously, don’t think like adding await first one, second one and third one etc.

What’s wrong in the code ?

It wouldn’t block your UI but it will be waiting for all tasks to be complete in side for loop.

What is the fix?

Fix is keep the tasks in collection, in the above example it is in array and then call Task.WhenAll on full collection. what is this WhenAll? how it is different? In Badexample 2 code block firing and waiting for all 5 tasks one after other. where a in WhenAll, you fire all 5 tasks at once and come back once it done. example: Multiple file upload

Bad example3: Bad threading practices

You have to be mindful when writing await in Xamarin forms(mobile apps) as everything run under main thread. example: you have a button on mobile app and it executes on mainthread when you click.

once await task is complete then what thread it is continuing with afterwards? is it still main thread? or is it different thread? developers has to think about this and understand the execution. It came from main thread and you have to be mindful where it run afterwards! Your app will be unresponsive for the period of time that PrintThreadCheck() method logic takes

What is the fix?

The fix is tricky and confusing and scares me alot !! use the magic key-word ConfigureAwait(false). By default task will have ConfigureAwait to true that means it is returning on the context of whatever is calling which was main thread in Xamarin forms. So when we say ConfigureAwait(false) then it means dont return on main thread and return on different thread and we dont have to specify what thread it is as Framework takes care of it.

What the above code guarantees is it wouldn’t run on main thread!!! so how it is able to hear print status to come back and actually update the UI?? Behind the scenes Xamarin has bindings in setproperties that has an invoke inside mainthread.

Bad example4: Bad Exception handling

Try/Catch won’t catch an exception for a fire and forget task! example follows

In the above code if exception occur then it will never get printed!! this worst than app crashing!!

What is the fix?

use task.continue with, what task.continue does is, once task is complete regardless if we were waited it or not this continuation will happen and we can pass an action with task as parameter so we can inspect our task and log the exception message!! You can also set continuous options when exactly example only cancelled or faulted etc.

If you are wondering how GetStringWithTaskRunAsync look then following is the code

Thanks to James Montemagno for explaining the above and more information on async\await can be read from here. More documents on async programming can be read from here

About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.

Add Comment

TechBubbles Microsoft Technology BLOG

Follow me

Archives

Tag Cloud