I have the question, what is the difference between these two methods?
async private void Button_Click_1(object sender, RoutedEventArgs e)
{
1) The Async key work makes the method asynchrounous with no blocking, by time slicing. Async must exist with await, that tell to wait for the completion of the task, but all the stuff before will be executed.
async private void Button_Click_1(object sender, RoutedEventArgs e)
{
var task = Task.Delay(1000);
/*Do stuff*/
await task;
}
2) Just make a thread sleep only, any code above will not execute, only after the thread sleep finish the task.
private void Button_Click_2(object sender, RoutedEventArgs e)
{
Thread.Sleep(2000);
/*Do stuff*/
}
Theres a good read at msdn Asynchronous Programming with Async and Await!
Adding async
, by itself, does nothing other than allow the method body to use the await
keyword. A properly implemented async method won't block the UI thread, but an improperly implemented one most certainly can.
What you probably wanted to do was this:
async private void Button_Click_1(object sender, RoutedEventArgs e)
{
await Task.Delay(2000);
MessageBox.Show("All done!");
}
async
by itself will not enable asynchronous (non-blocking) method invocation.
You should use await
inside the async
function.
You should read this to have a better understanding of this capability.