我有以下代码:
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";
}
}
我想展示单击“同步”按钮(按钮 2)和单击“异步”按钮(按钮 3)之间的区别。单击两个按钮应该执行相同的耗时计算(在我的例子中,用“Thread.Sleep(5000)”表示)。目前使用异步和等待让我的客户卡住我认为这些关键字不应该阻止我的客户线程。我究竟做错了什么?