在同步方法里面使用Task及TaskFactory

List<MealOrderCheckExceptionViewModel> mealOrderCheckExceptionViewModels = new List<MealOrderCheckExceptionViewModel>();

List<Task<MealOrderCheckExceptionViewModel>> tasks = new List<Task<MealOrderCheckExceptionViewModel>>();
TaskFactory taskFactory = new();
if (!personModels.Any()) return pageResult;
foreach (var person in personModels)
{
     tasks.Add(taskFactory.StartNew(() => GetUserMealExceptionRecord(person, start, end)));
}

taskFactory.ContinueWhenAll(tasks.ToArray(), resTasks =>
{
     foreach (Task<MealOrderCheckExceptionViewModel> resTask in resTasks)
     {
          mealOrderCheckExceptionViewModels.Add(resTask.Result);
     }
}).Wait();

posted @ 2022-05-13 11:39  静下心来邹  阅读(59)  评论(0编辑  收藏  举报