创建了以下控制台应用程序后,我有点困惑为什么它似乎同步运行而不是异步运行:
class Program { static void Main(string[] args) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var total = CreateMultipleTasks(); stopwatch.Stop(); Console.WriteLine("Total jobs done: {0} ms",total.Result); Console.WriteLine("Jobs done in: {0} ms",stopwatch.ElapsedMilliseconds); } static async Task<int> CreateMultipleTasks() { var task1 = WaitForMeAsync(5000); var task2 = WaitForMeAsync(3000); var task3 = WaitForMeAsync(4000); var val1 = await task1; var val2 = await task2; var val3 = await task3; return val1 + val2 + val3; } static Task<int> WaitForMeAsync(int ms) { Thread.Sleep(ms); return Task.FromResult(ms); } }
运行应用程序时,输出为:
Total jobs done: 12000 ms
Jobs done in: 12003 ms
我原以为是会像以下一样:
Total jobs done: 12000 ms
Jobs done in: 5003 ms
这是因为当我使用Thread.Sleep方法时它会停止进一步执行整个应用程序吗?或者我错过了一些重要的东西?
解决方法
您以同步方式运行任务.你可以这样做:
static async Task<int> CreateMultipleTasks() { var task1 = Task.Run<int>(() => WaitForMeAsync(5000)); var task2 = Task.Run<int>(() => WaitForMeAsync(3000)); var task3 = Task.Run<int>(() => WaitForMeAsync(4000)); Task.WaitAll(new Task[] { task1,task2,task3 }); return task1.Result + task2.Result + taks3.Result; }
连续使用三个await将不会并行运行任务.它将在等待时释放线程(如果你使用等待Task.Delay(ms),因为Thread.Sleep(ms)是一个阻塞操作),但当task1处于“休眠”时,当前执行将不会继续task2.