Talk is cheap, Show you the code first!
private async void Form1_Load(object sender, EventArgs e)
{
var t = Task.Run(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(2));
return "hello";
});
lb.Text = await t;
timer1.Enabled = true;
timer1.Interval = 2000;
}
private async void timer1_Tick(object sender, EventArgs e)
{
var t = Task.Run(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(5));
return string.Format("{0:U}", DateTime.Now);
});
lb.Text = await t;
}
提示一下await的作用是分裂,await之前和之后会在两个线程中处理。
具体文章可参考
C# 彻底搞懂async/await - 五维思考 - 博客园
https://www.cnblogs.com/zhaoshujie/p/11192036.html