I've decided to do a series of posts of Async Await which is the latest and greatest way to achieve asynchronous code in .Net. I'm doing this primarily as a brain dump of what helped me learn this very cool new(ish) feature.
So how does it work?
Well at a very simple level there are two new keyswords async and await. You mark you're method using the async keyword and return a Task or a Task<TResult>. You can also return void but this is NOT recommended except for top level event handlers.You then use the other keyword await inside your method body. Lets look at an example:-
private async Task AwaitAndProcessTasksAsync(Task<int> task)
{
var result = await task;
Console.WriteLine(result);
}
So above we have a very simple example of a method accepting a Task<int> and returning a Task. Now the first thing that struck me about this was where is the return statement? I mean we are returning a Task but nowhere in this method do a I see a return statement. Well it turns out that this is actually a void method, in fact it is exactly the same in functionality as the code below:-
Code:
private async void AwaitAndProcessTasksAsync(Task<int> task)
{
var result = await task;
Console.WriteLine(result);
}
There is a subtle but important difference though. Without the Task we cannot be sure when and if the method completed successfully. Hence we should always return Task. Should we want a return value then we simply need to return the value and it will be wrapped in a Task for us.
No comments:
Post a Comment