注意点
async、await关键字一般成对出现,表示是异步函数。
同时,被调用的异步函数返回值类型是Task。
// 按钮事件
private void BtnTaskAwait_Click(object sender, EventArgs e)
{
Debug.WriteLine("BtnTaskAwait_Click begin.");
ExecuteTask(sender, e);
Debug.WriteLine("BtnTaskAwait_Click end.");
}
// 执行短暂的同步操作,启动异步操作
private async void ExecuteTask(object sender, EventArgs e)
{
Debug.WriteLine("ExecuteClickTaskAsync begin.");
textBox1.Text = "";
progressBar1.Visible = true;
await DoSomethingAsync(sender, e);
progressBar1.Visible = false;
Debug.WriteLine("ExecuteClickTaskAsync end.");
}
// 执行耗时的异步操作
private async Task DoSomethingAsync(object sender, EventArgs e)
{
//await Task.Run(() =>
//{
// //Task.Delay(TimeSpan.FromSeconds(5));
// System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
//});
await Task.Run(() =>
{
textBox1.Invoke((MethodInvoker)(() =>
{
textBox1.Text = "Task async UI: Sleep 5 second.";
}));
var sw = new Stopwatch();
sw.Start();
while (sw.Elapsed.TotalSeconds < 5)
{
int val = (int)(sw.Elapsed.TotalSeconds / 5 * 100) % 100;
progressBar1.Invoke((MethodInvoker)(() =>
{
progressBar1.Value = val;
}));
Task.Delay(TimeSpan.FromMilliseconds(1));
}
textBox1.Invoke((MethodInvoker)(() =>
{
textBox1.Text = "Task async UI: Finished.";
}));
});
}
以下Debug输出,可以看出是异步执行的。
BtnTaskAwait_Click begin.
ExecuteClickTaskAsync begin.
BtnTaskAwait_Click end.
ExecuteClickTaskAsync end.