Asynchronous programming in C# sounds very easy as there are only one keyword async and one operator await involved. But there could be a lot confusion for a beginner.
To start, we need know that an asnyc method doesn’t need to have await operator inside its implementation. But await operator has to be in an async method. If a statement has await in a regular method without async keyword, there is compiler error:
“Error CS4033 The ‘await’ operator can only be used within an async method. Consider marking this method with the ‘async’ modifier and changing its return type to ‘Task’. ”
Any method you want to use operator await to call, its return types usually are Task or Task<TResult>. It can’t be void or a type without GetAwaiter method (or extension method) implemented. Compiler should tell you that.
Let’s take a look at the sample WinForm code below:
In the code above, the event handler code and DoSomething() method are the same as synchronous code. CallMethod() is asynchronous. When we click on button, the message box immediate pops up, but the button text changes only after more than 10 seconds passes.
If we remove await operator, CallMethod() will block UI thread, and our form freezes for at least 10 seconds.
This is our starting point. We will dig deeper into it.