I have an asynchronous method like this:
private async Task TaskAsync()
{
await Task.Run(() => Task.Delay(2000));
}
I then call it in a button-click event, which I've declared like this:
private async void button1_Click(object sender, EventArgs e)
{
await TaskAsync();
MessageBox.Show("Afterwards.");
}
Now, when I click on the button, TaskAsync()
is literally awaited on, and the message box isn't shown until TaskAsync()
has finished executing. However, when I remove the await
command when calling TaskAsync()
in the click event, then execution immediately jumps to the message box.
Am I doing something wrong here? Is this normal behavior of async...await?
My project is a .NET Core 5 C# winform project.
CodePudding user response:
There are two problems here. First, the TaskAsync
method is using Task.Run
to run another async method. That just wastes a thread. It should be just :
private async Task TaskAsync()
{
await Task.Delay(2000);
}
if not
private Task TaskAsync()=>Task.Delay(2000);
Second, if a Task isn't awaited execution will proceed immediately. That's the whole point of using await
- awaiting an already executing asynchronous task to complete without blocking the calling thread.
The original code is equivalent to :
private async void button1_Click(object sender, EventArgs e)
{
await Task.Delay(2000);
MessageBox.Show("Afterwards.");
}
Without await
, the task returned by Task.Delay()
will be ignored and the message box will be displayed immediately.