Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async modifier in C#

Tags:

I have the question, what is the difference between these two methods?

    async private void Button_Click_1(object sender, RoutedEventArgs e)     {         Thread.Sleep(2000);     }      private void Button_Click_2(object sender, RoutedEventArgs e)     {         Thread.Sleep(2000);     } 

Both of them block my UI. I know that I must start another thread to avoid blocking, but I have found:

"An async method provides a convenient way to do potentially long-running work without blocking the caller's thread".

I'm a bit confused.

like image 971
raki Avatar asked Jul 01 '13 14:07

raki


2 Answers

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!"); } 
like image 144
Servy Avatar answered Oct 12 '22 15:10

Servy


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.

like image 39
Liel Avatar answered Oct 12 '22 14:10

Liel