Speaking from the perspective of a lifelong Catholic, I think Catholicism can often get too caught up in doctrine and tradition. I’m sure other religions suffer from this problem as well. I respect…
The async
and await
keywords were introduced on .NET 4.0.
In the past asynchronous operations were achieved by invoking methods and handling callbacks. Or by starting new threads and having to handle them. That way you have to focus on handling the asynchronous operations and it also caused your code to be split all over the place due the callbacks and complex error handling.
The async
and await
makes it possible so that you can create your code as you would when performing synchronous operations.
I am going to build a screen with a progress bar and some buttons, like this:
The XAML code for it is:
On this screen I have a couple of run buttons and a “Do something else” button.
When I click the Run button I am going to fill the progress bar from 0 to 100 without any asynchronous operations:
If I try to click “Do something else” button while the run command is executing nothing visual is going to happen because the UI will be frozen, but it will still queue your actions.
We can change this code to perform asynchronous by tagging the method with async
. When we say a method is async
we have to await
some action. In this case I will await
a task to run:
The await
keyword is only available inside an async
method. It means that it is going to wait for the operation to end before continuing, but only inside the async method. It means it will not lock our UI thread, it locks another thread.
If I run my application now that my method is in an asynchronous format I can “Do something else” at the same time my process is running:
An async
method accepts 3 types of return values: void
, Task
or Task<T>
.
When you return void
you are saying that the operation will happen asynchronous and will not return anything at all.
When you return Task
you are saying that the operation is returning.
When you return Task<T>
you are saying that the operation is returning and it returns a value of type T
.
This way you can have your asynchronous operations isolated in methods and it looks almost like you are just building normal code. You code stays very clean and organized.
Back in March 2020 when the pandemic first started, I found myself caught up in the news every night and I was allowing it to heighten my anxiety. I didn’t see the negative effects at the time it was…
I have accomplished a memorable wedding album for my sister. Since my sister decided to get merry, she told me that she really wants to take wedding photo in Korea. She told me what style she likes…
My online identity revolves around an image of a cartoon ape, a metaverse pseudonym for my real-world self. The bowler hat and Patagonia-style vest, representing both past and present styles in the…