在C#中异步修改 [英] Async modifier in C#
问题描述
我有问题,就是这两种方法之间的区别?
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);
}
他们都挡住了我的UI。我知道我必须开始另一个线程避免阻塞,但我发现:
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".
我有点糊涂了。
推荐答案
添加异步
,本身并没有什么其他的不是让方法体使用的await
关键字。一个正确实施的异步方法不会阻塞UI线程,但不正确实现的一个肯定能
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!");
}
这篇关于在C#中异步修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!