C#异步编程
同步方法:可以认为程序是按照你写这些代码时所采用的顺序执行相关的指令的。
异步方法:可以在尚未完成所有指令的时候提前返回,等到该方法等候的那项任务执行完毕后,在令这个方法从早前还没执行完的那个地方继续往下运行。
举例:
同步方法代码如下:
定义三个方法
private void Batch11()
{
Thread.Sleep(1000);
textBox1.Text = "11";
}
private void Batch22()
{
Thread.Sleep(1000);
textBox2.Text = "22";
}
private void Batch33()
{
Thread.Sleep(1000);
textBox3.Text = "33";
}
写一个按钮事件去调用
private void button1_Click(object sender, EventArgs e)
{
Stopwatch stopwatch = Stopwatch.StartNew();
Batch11();
Batch22();
Batch33();
MessageBox.Show(string.Format("同步结束共用时{0}秒!", stopwatch.ElapsedMilliseconds / 1000));
}
结果用时3秒
异步方法实现:
private async Task Batch1()
{
await Task.Delay(1000);
textBox1.Text = "1";
}
private async Task Batch2()
{
await Task.Delay(1000);
textBox2.Text = "2";
}
private async Task Batch3()
{
await Task.Delay(1000);
textBox3.Text = "3";
}
private void button2_Click(object sender, EventArgs e)
{
Batch();
}
private async Task Batch()
{
Stopwatch stopwatch = Stopwatch.StartNew();
List<Task> listTask = new List<Task>();
listTask.Add(Batch1());
listTask.Add(Batch2());
listTask.Add(Batch3());
await Task.WhenAll(listTask);
MessageBox.Show(string.Format("异步演示结束共用时{0}秒!", stopwatch.ElapsedMilliseconds / 1000));
}
结果用时1秒