从Task.Run获取结果

时间:2016-12-07 12:05:44

标签: c# .net asynchronous async-await task-parallel-library

嗨,大家好我试图从Task.Run得到一些结果,但我无法弄清楚如何

我有多个方法可以并行运行并提取结果: 这是方法之一

protected override async Task<IList<EducationDTO>> GetEmployeesEducation(int userId)
{
    IList<EducationDTO> userEducation = await EducationService.GetEducationsByUserId(userId);        
    return userEducation.Count > 0 ? userEducation : null;
}

这里所有方法都将并行运行

public async Task<DTOs.EmployeeDTO> GetEmployeeInfo(int userId)
{
    EmployeeDTO employee = new EmployeeDTO();

    Task task = Task.Run(() => {
        Parallel.Invoke(
        async () => { await GetEmployeeLanguages(userId); },
        // ...
    });
    task.Wait();

    /// extract result and process how ???

    return employee;
}

3 个答案:

答案 0 :(得分:2)

  

我有多种方法可以并行运行并提取结果

实际上,您希望同时运行 。 &#34;并行&#34;意味着CPU绑定代码,但您的代码是I / O绑定的。

所以,根本不要使用Parallel;这是错误的工具:

public async Task<DTOs.EmployeeDTO> GetEmployeeInfo(int userId)
{
  EmployeeDTO employee = new EmployeeDTO();

  // Start all tasks
  var languagesTask = GetEmployeeLanguages(userId);
  var educationsTask = GetEmployeesEducation(userId);
  var outExperiencesTask = GetEmployeesOutExperience(userId);
  var ubiExperiencesTask = GetEmployeesUbiExperience(userId);

  // Asynchronously wait for them all to complete
  await Task.WhenAll(languagesTask, educationsTask, outExperiencesTask, ubiExperiencesTask);

  // Retrieve results
  employee.Languages = await languagesTask;
  employee.Educations = await educationsTask;
  employee.OutExperiences = await outExperiencesTask;
  employee.UbiExperiences = await ubiExperiencesTask;

  return employee;
}

答案 1 :(得分:0)

创建任务并立即等待它是没有用的,所以放弃StartNew

也不需要先Wait然后获取ResultResult隐式等待。该方法根本不是异步的,您可以放弃async Task<>并直接返回EmployeeDTO ...

答案 2 :(得分:-2)

所以这是我的发现

public async Task<DTOs.EmployeeDTO> GetEmployeeInfo(int userId)
{

    EmployeeDTO employee = new EmployeeDTO();

    Task<EmployeeDTO> task = Task.Factory.StartNew(() =>
    {
        Parallel.Invoke(
         () => { employee.Languages = GetEmployeeLanguages(userId).Result; },
         () => { employee.Educations = GetEmployeesEducation(userId).Result; },
         () => { employee.OutExperiences = GetEmployeesOutExperience(userId).Result; },
         () => { employee.UbiExperiences = GetEmployeesUbiExperience(userId).Result; });

        return employee;
    });
    task.Wait();

    return task.Result;

}

如果您有任何其他建议或更好的方法,请分享。谢谢。