根据条件并行调用方法

时间:2018-09-19 07:38:19

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

public IList<Student> GetStudentList()
{
    var students = new List<Student>();
    if(getOtherSchoolStudents)
    {
        var otherSchoolStudents  = GetOtherSchoolStudents();
        students.AddRange(otherSchoolStudents);
    }
    var currentSchoolStudents = GetCurrentSchoolStudents();
    students.AddRange(currentSchoolStudents)
    return students;
}

这里,当getOtherSchoolStudentstrue时,我想并行运行方法GetOtherSchoolStudents()GetCurrentSchoolStudents()。我知道我可以将GetCurrentSchoolStudents()移到条件范围内,并如下所示并行运行

public IList<Student> GetStudentList()
{
    var students = new List<Student>();
    if(getOtherSchoolStudents)
    {
        var otherSchoolStudents  = GetOtherSchoolStudents(); // run in parallel
        var currentSchoolStudents = GetCurrentSchoolStudents(); // run in parallel
        students.AddRange(otherSchoolStudents);
        students.AddRange(currentSchoolStudents)
    }
    else
    {
        var currentSchoolStudents = GetCurrentSchoolStudents(); 
        students.AddRange(currentSchoolStudents);
    }
    return students;
}

还有其他方法吗?

1 个答案:

答案 0 :(得分:1)

最简单的方法可能是并行调用两个get操作:

public IList<Student> GetStudentList()
{
    List<Student> currentSchoolStudents;
    List<Student> otherSchoolStudents; 

    Parallel.Invoke(
    { currentSchoolStudents = GetCurrentSchoolStudents(); }
    { otherSchoolStudents = getOtherSchoolStudents 
                          ? GetOtherSchoolStudents() 
                          : new List<Student>(); }
    );

    var students = new List<Student>();
    students.AddRange(otherSchoolStudents);
    students.AddRange(currentSchoolStudents)
    return students;
}

这假设您的操作返回了List<Student>,如果它们返回了其他内容,例如Student[],则需要相应地更改类型。