Back
Close

Your Ultimate async / await Tutorial in C#

AramT
331.2K views

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.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io