Your Ultimate async / await Tutorial in C#
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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
orTask
orTask<T>
, whereT
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 becomeGetUserNameAsync
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.