标签:
这次来介绍一些用法:
await一批任务,不等候其它任务完成,直接执行后续的任务。
class Program { static void Main(string[] args) { var taskA = DelayAndRerutnAsync(2); var taskB = DelayAndRerutnAsync(3); var taskC = DelayAndRerutnAsync(1); var tasks = new[] {taskA, taskB, taskC}; var processingTasks= (from t in tasks select AwaitAndProcessAsync(t)).ToArray(); Task.WhenAll(processingTasks); Console.Read(); } static async Task<int> DelayAndRerutnAsync(int val) { await Task.Delay(TimeSpan.FromSeconds(val)); Console.WriteLine("等候了{0}",val); return val; } static async Task AwaitAndProcessAsync(Task<int> task) { var result = await task; Console.WriteLine(result); } }
从打印出的结果可以看到,在等候1秒的方法执行完成后并没有等待其它方法的执行,而是直接执行后面的异步方法。
下面介绍一种使用匿名方法的写法
class Program { static void Main(string[] args) { var taskA = DelayAndRerutnAsync(2); var taskB = DelayAndRerutnAsync(3); var taskC = DelayAndRerutnAsync(1); var tasks = new[] {taskA, taskB, taskC}; var processingTasks = tasks.Select(async task => { var result = await task; Console.WriteLine(result); }); Task.WhenAll(processingTasks); Console.Read(); } static async Task<int> DelayAndRerutnAsync(int val) { await Task.Delay(TimeSpan.FromSeconds(val)); Console.WriteLine("等候了{0}",val); return val; } }
标签:
原文地址:http://www.cnblogs.com/harpz/p/4913984.html