Your Ultimate async / await Tutorial in C#

AramT
5,442 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Turning a normal method to become asynchronous and make it use the async / await keywords, should be achieved by the following changes:

  • Method definition should include the keyword async, this keyword by itself doesn't do anything except enabling you to use the keyword await within the method.

  • Method return type should change to return either void or Task or Task<T> , where T is the return data type, so in this example it will become

public async Task<String> GetUserNameAsync(){ }

  • According to the naming convention, an asynchronous method name should end with the word 'Async' , so if you have a method with name GetUserName, it should become GetUserNameAsync  

When you add the keyword async to the method definition, it will enable you to use the await keyword within this method, which means you can await the method in the way you need. and if you do not include the keyword await, then the method will be treated as a normal or synchronous method.

An important note here is that even though returning void in an async method is allowed, it should not be used in most cases, as the other 2 return types Task and Task<T> represent void and T subsequently, after the awaitable method completes and returns result. So the use of void as return type should be only limited for event handlers.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content