我们可以在循环中使用异步方法调用

时间:2012-05-15 05:37:17

标签: c# asp.net multithreading .net-4.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
    }
}

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分:0)

以下是代码的Reactive Framework(Rx)版本:

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

这也会产生并行结果。