考虑以下Winform代码。当我点击按钮时,希望异步方法不会阻塞它所在的UI线程。
然而,我发现在异步方法调用期间按钮被冻结了... 如果是这样的话,异步方法有何意义呢?我很困惑。
namespace WindowsFrmAsyn
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
async private void button1_Click(object sender, EventArgs e)
{
int contentlength = await AccessTheWebAsync();
tbResult.Text =
string.Format("Length of the downloaded string: {0}.", contentlength);
Debug.WriteLine(tbResult.Text);
}
async Task<int> AccessTheWebAsync()
{
Debug.WriteLine("Call AccessTheWebAsync");
Thread.Sleep(5000);
Debug.WriteLine("Call AccessTheWebAsync done");
tbResult.Text = "I am in AccessTheWebAsync";
return 1000;
}
}
}