这是一个简单的 WinForm 应用程序,用于试验 await/async 关键字。下面是按钮的事件处理程序。
我快速点击按钮两次,间隔小于 3000ms 所以后台线程还没有完成。
private Task<String> f()
{
return Task.Run<String>(() =>
{
Thread.Sleep(3000);
return Thread.CurrentThread.ManagedThreadId.ToString();
}
);
}
private async void async_btn_Click(object sender, EventArgs e)
{
Task<String> wait_task = f();
//Code 1, this outputs first 3, and then 3 is REPLACED with 4.
//this.async_lbl.Text += await wait_task; //3 -> 4
//Code 2, this outputs first 3, and then 34.
//String wait_value = await wait_task;
//this.async_lbl.Text += wait_value; //3 -> 34
}
为什么1和2的输出不同?
谢谢!
添加
下面是反映的代码:
3 -> 34
// WindowsFormsApplication1.Form1
private async void async_btn_Click(object sender, EventArgs e)
{
Task<string> task = this.f();
string str = await task;
Label expr_AA = this.async_lbl;
expr_AA.Text += str;
}
3 -> 4
// WindowsFormsApplication1.Form1
private async void async_btn_Click(object sender, EventArgs e)
{
Task<string> task = this.f();
Label label = this.async_lbl;
label.Text += await task;
}