WhenAll 与 WaitAll 的区别
#region async Task await /// <summary> /// commit /// </summary> /// <param name="mallCode">code</param> /// <returns>json</returns> [HttpGet] public async Task<ResultDataModel<JObject>> TaskTest(string mallCode) { var gameQQ = GameQQ(1, 2); var gameWX = GameWX(1, 2); var gameLOL = GameLOL(1, 2); var breakfastTasks = new List<Task> { gameQQ, gameWX, gameLOL }; //while (breakfastTasks.Count > 0) //{ // Task finishedTask = await Task.WhenAny(breakfastTasks);//任何提供的任务已完成时,创建将完成的任务。 WhenAll // if (finishedTask == gameQQ) // { // System.Diagnostics.Debug.WriteLine("gameQQ 开完"); // } // else if (finishedTask == gameWX) // { // System.Diagnostics.Debug.WriteLine("GameWX 发完"); // } // else if (finishedTask == gameLOL) // { // System.Diagnostics.Debug.WriteLine("GameLOL 打完"); // } // breakfastTasks.Remove(finishedTask); //} //主线程(当前请求)等和不等的区别 ,返回值为Task //Task.WhenAll(breakfastTasks); //await Task.WhenAll(breakfastTasks); Task.WaitAll(breakfastTasks.ToArray()); //与 WhenAll 相比,返回值为void 。和写了 await 的WhenAll 没有区别 int asd = 0;//其他代码 return StateMessage.GetSuccess("1000", "", new JObject()); } private async Task<int> GameQQ(int password,int account) { await Task.Delay(3000); System.Diagnostics.Debug.WriteLine("GameQQ"); return 0; } private async Task<int> GameWX(int password, int account) { await Task.Delay(1000); System.Diagnostics.Debug.WriteLine("GameWX"); return 1; } private async Task<int> GameLOL(int password, int account) { await Task.Delay(500); System.Diagnostics.Debug.WriteLine("GameLOL"); return 2; } #endregion
WaitAll 为 void ,WhenAll 为 task。 用法无区别