I never had a good chance to go deep into async/await
, so I have just a gist of what it does.
So I tried it in WinForms app like this:
private async void button2_Click(object sender, EventArgs e)
{
// In below line I understand the Task is created and scheduled to execute, which in this
// simple case means, that it executes right away asynchronously.
var task = Task.Factory.StartNew(() =>
{
Task.Delay(5000).Wait();
return 12;
});
// Here we wait for the task to finish, so we don't see MessageBox yet.
var res = await task;
MessageBox.Show("Result is :" + res);
}
My question is, since we are waiting on await
I expected to block UI thread, since we can go any further in that thread (to the line with MessageBox
). So UI thread actually stops on method with event hadnler.
But, to my surprise, windows is responsive and everything works very well, but I didn't expect that. Can anybody explain me what is going on?
After reading this post, I still have a doubt, if await
is asynchronous and doesn't block UI thread in my example, why the thread doesn't proceed to next line with MessageBox
? How the UI thread proceeds then?
Is good idea that code after await
is just another Task
, like in ContinueWith
? But it comes back to UI context?