i have the following code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
this.Background = Brushes.Red;
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
int res = WaitFiveSecMethod();
this.text2.Text = res.ToString();
}
private int WaitFiveSecMethod()
{
Thread.Sleep(5000);
return 5;
}
private async void Button_Click_3(object sender, RoutedEventArgs e)
{
var res = await WaitFiveSecMethodAsync();
this.text1.Text = res;
}
private async Task<string> WaitFiveSecMethodAsync()
{
Thread.Sleep(5000);
return "5";
}
}
I want to show the difference between clicking the “sync” button (button 2) and clicking the “async” button (button 3). clicking both buttons should do the same time-consuming calculations (in my case represented with “Thread.Sleep(5000)”).
Currently using async and wait make my client stuck i thought these keywords shouldn’t block my client thread.
what am i doing wrong?
Your code below works synchronously and block UI, not async:
Remember async has just responsibility to enable
awaitkeyword, if you don’t haveawait,asyncis meaningless and turn to synchronous. So, async method must have at least oneawaitkeyword inside.The better way is, you should delay by awaiting
Task.Delaywhich does not block your UI thread: