简体   繁体   中英

Is this method of reporting progress from a parrallel thread better or worse then a lock?

I implemented a method for reporting progress from a parallel select. It works fine. But after looking at some answers to similar problems on stack overflow I wonder if my approach was overkill or if it has merit.

My current method is just as fast as not reporting progress and doing a AsParrallel on the whole collection. However my interest is that limitation of 12 threads. How this might impact the performance on other machines.

int count = ids.Count();
const int takeValue = 12;
List<ImportantDataDecorator> parrallel = new List<ImportantDataDecorator>();
for (int i = 0; ids.Count > 0; i += takeValue)
{
    int take = takeValue;
    if (take > ids.Count)
    {
        take = ids.Count;
    }

    var idsToProcess = ids.Take(takeValue);
    var processed = idsToProcess.AsParallel().Select(x =>
    {
        var value = GetValue(x, divBuffer, mask);

        return new ValueDecorator(value, x);
    }).ToList();

    parrallel.AddRange(processed);
    ids.RemoveRange(0, take);


    int remaining = i;
    float percent = (remaining/(float)count) * 100.0f;

    if (backgroundWorker != null)
    {
        backgroundWorker.ReportProgress((int) percent);

        if (backgroundWorker.CancellationPending)
            return;
    }

}

Splitting the work and reporting back the progress doesn't seem to be taking up much computational time. But the application is doing some(even if little) work to do that.

My current method is just as fast as not reporting progress and doing a AsParrallel on the whole collection

You can try your method with much larger data and Benchmark both strategies and pick the better one.

However splitting up processing and doing additional work of reporting back progress will cost you some additional time(which will be noticeable for very large data). You should decide between whether Progress report adds value to your application that makes up for the additional time.

AsParallel() depends on various factors such as computational loads, number of system cores etc. This particular method might run faster in your system and perform worse on a system with less computational power.
See this link for speeding up PLINQ : https://msdn.microsoft.com/en-us/library/dd997399(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM