开发者

Parallel on List of Objects?

I have .net 3.5 an开发者_如何学God I want to use Parallel.ForEach. I have List of Accounts which needs to be refreshed from other system. For this I am thinking of create list of account object; and I will call accountObj.Process method which will does processing. I want to make sure my approach is right and things will be in place for this ?

If anyone of you have already done this then can you point me to correct implementation/example etc...

How does Paralle.ForEach works internally ? Does it create one thread for each item of for loop or it works with finite set of threads ?

Ocean


Parallel.ForEach sounds like a perfectly reasonable approach. It doesn't create a thread per item - it partitions the list into tasks for different threads, but keeps a bound on the number created. If your tasks are network-bound, I believe PFX may notice that and increase the number of threads being used. It's certainly work giving it a try.

I suggest you read the parallelism book from the MS Patterns and Practices group for more detailed advice.


I suggest you read the parallelism book from the MS Patterns and Practices group for more detailed advice.

Thanks Jon :)

The credit review sample in the book chapter 2 shows how to do this. You can actually use Parallel.ForEach

        Parallel.ForEach(accounts.AllAccounts, account =>
        {
            Trend trend = SampleUtilities.Fit(account.Balance);
            double prediction = trend.Predict(account.Balance.Length + NumberOfMonths);
            account.ParPrediction = prediction;
            account.ParWarning = prediction < account.Overdraft;
        });

Or PLINQ:

        accounts.AllAccounts
            .AsParallel()
            .ForAll(account =>
                {
                    Trend trend = SampleUtilities.Fit(account.Balance);
                    double prediction = trend.Predict(account.Balance.Length + NumberOfMonths);
                    account.PlinqPrediction = prediction;
                    account.PlinqWarning = prediction < account.Overdraft;         
                });

In both cases the TPL assigns work from a pool of threads, the .NET ThreadPool. The TPL uses adaptive range partitioning and adaptive concurrency to maximize throughput. You can use a customer Partitioner to get finer control over how the collection is split up over different threads. You can also set the maximum degree of concurrency with MaxDegreeOfParallelism. In general it's better to let the TPL do it's own optimization unless you see perfromance issues.

Note: If you only have .NET 3.5 then Task Parallel Library (TPL) features are not present. At one point there was a CTP of TPL for 3.5 but that's no longer available. I believe that the TPL binaries are also part of the Rx for .NET 3.5 download. This might give you a chance to use TPL with 3.5.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜