1.代码部分--WhenAll
namespace TaskWhenAll
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}public async Task Calibration()//--Async修改{// 以异步方式执行命令// 异步调用同步的 CommandEx 方法Task task1 = Task.Run(() => CommandEx(10*10000));Task task2 = Task.Run(() => CommandEx(100 * 10000));Task task3 = Task.Run(() => CommandEx(1000 * 10000));// 等待所有命令异步完成await Task.WhenAll(task1, task2, task3);Debug.WriteLine($"Task1.2.3计算完毕");// 检查任务结果,返回失败信息}public void CommandEx(float num){for (int i = 0; i < num; i++){i = i-0;}Debug.WriteLine($"{num}计算完毕");}private async void Button_Click(object sender, RoutedEventArgs e){await Calibration();}}
输出结果:
2.代码_WhenAll不等待
namespace TaskWhenAll
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}public async Task Calibration()//--Async修改{// 以异步方式执行命令// 异步调用同步的 CommandEx 方法Task task1 = Task.Run(() => CommandEx(10*10000));Task task2 = Task.Run(() => CommandEx(100 * 10000));Task task3 = Task.Run(() => CommandEx(1000 * 10000));// 等待所有命令异步完成//await Task.WhenAll(task1, task2, task3);Debug.WriteLine($"Task1.2.3计算完毕");// 检查任务结果,返回失败信息}public void CommandEx(float num){for (int i = 0; i < num; i++){i = i-0;}Debug.WriteLine($"{num}计算完毕");}private async void Button_Click(object sender, RoutedEventArgs e){await Calibration();}}
输出结果:
3.如果需要更细致观察线程切换,可以打印出执行每个单步的线程ID