1. 任务完成时的处理
1 class Program 2 { 3 private static void Main(string[] args) 4 { 5 ProcessTaskAsync(); 6 Console.ReadLine(); 7 } 8 static async Task ProcessTaskAsync() 9 { 10 //按顺序await每个任务 11 //创建任务队列 12 Task<int> taskA = DelayAndReturnAsync(5); 13 Task<int> taskB = DelayAndReturnAsync(2); 14 Task<int> taskC = DelayAndReturnAsync(8); 15 var tasks1 = new[] { taskA, taskB, taskC }; 16 Console.WriteLine("============================"); 17 Console.WriteLine("============按顺序==========="); 18 foreach (var task in tasks1) 19 { 20 var result = await task; 21 Console.WriteLine(result); 22 } 23 //输出5,2,8 24 25 //按处理速度 26 //创建任务队列 27 Task<int> task1 = DelayAndReturnAsync(5); 28 Task<int> task2 = DelayAndReturnAsync(2); 29 Task<int> task3 = DelayAndReturnAsync(8); 30 var tasks2 = new[] { task1, task2, task3 }; 31 Console.WriteLine("============================"); 32 Console.WriteLine("==========按处理速度========="); 33 var processingTasks = tasks2.Select(async t => 34 { 35 var result = await t; 36 Console.WriteLine(result); 37 }).ToArray(); 38 //等待全部处理过程完成 39 await Task.WhenAll(processingTasks); 40 //输出2,5,8 41 } 42 static async Task<int> DelayAndReturnAsync(int val) 43 { 44 await Task.Delay(TimeSpan.FromSeconds(val)); 45 return val; 46 } 47 }
2. 等待任意一个任务完成
1 class Program 2 { 3 private static void Main(string[] args) 4 { 5 FirstRespondingUrlAsync(); 6 Console.ReadLine(); 7 } 8 static async Task FirstRespondingUrlAsync() 9 { 10 var httpClient = new HttpClient(); 11 string url1 = "https://www.baidu.com"; 12 string url2 = "https://www.cnblogs.com/"; 13 //并发地开始两个下载任务 14 Task<byte[]> task1 = httpClient.GetByteArrayAsync(url1); 15 Task<byte[]> task2 = httpClient.GetByteArrayAsync(url2); 16 //等待任意一个任务完成 17 Task<byte[]> completedTask = await Task.WhenAny(task1, task2); 18 //返回从URL得到的数据长度 19 byte[] data = await completedTask; 20 Console.WriteLine(data.Length); 21 } 22 }