0

我想通过使用线程来优化性能。

public delegate int DelegateGetMarkOfSubject(int subjectid, int studentid);

int TotalMark = 0;

public void GetTotalMark(int StudentId)    
{
    TotalMark = 0;

    List<Subjects> lstSubj = GetSubjectList(StudentId);
    Waithandle[] waitHandler = new waitHandler[10];

    DelegateGetMarkOfSubject delmarkOfSubj = new DelegateGetMarkOfSubject(GetMark);

    foreach(var subject in lstSubj)
    {
        IAsync result_subject.id = delmarkOfSubj.BeginInvoke(subject.id, StudentId, new AsyncCallBack(GetMarkComplete), null);
        waitHandler.add(result_subject.id.AsyncHandle);
    }

    WaitHandle.WaitAll(waitHandler);
    return TotalMark;
}


GetMarkComplete(Iasynch argument)
{
    DelegateGetMarkOfSubject  del = (DelegateGetMarkOfSubject )((Asynchresult ar)).AsynDelegate;

    newMark = del.EndInvoke(argument)

    if(LockingCondition)
    {
        //PutLock

        TotalMark += newMark;

        //Release Lock
    }
}
4

2 回答 2

1

为什么不使用 PLINQ?

class Subject
{
    public Int32 Mark { get; set; }
}

        var subjects = new List<Subject>
        {
            new Subject { Mark = 50 },
            new Subject { Mark = 75 },
            new Subject { Mark = 81 },
        };

        Console.WriteLine(subjects.AsParallel().Sum(subject => subject.Mark));
于 2012-05-15T06:38:09.803 回答
0

这是您的代码的反应式框架 (Rx) 版本:

var totalMarks = (
    from subject in lstSubj.ToObservable()
    from mark in Observable.Start(() => GetMark(subject.id, StudentId))
    select mark).Sum().Last();

这也会产生并行的结果。

于 2012-05-15T07:23:42.520 回答