Christofer Ohlsson
Christofer Ohlsson

Reputation: 3145

C# Splitting loop on multiple threads

I have a task that essentially loops through a collection and does an operation on them in pairs (for int i = 0; i < limit; i+=2 etc.) And so, most suggestions I see on threading loops use some sort of foreach mechanism. But that seems a bit tricky to me, seeing as how I use this approach of operating in pairs.

So what I would want to do is essentially replace:

DoOperation(list.Take(numberToProcess));

with

Thread lowerHalf = new Thread(() => => DoOperation(list.Take(numberToProcess/2)));

Thread lowerHalf = new Thread(() => => DoOperation(list.getRange(numberToProcess/2, numberToProcess));

lowerHalf.Start();
upperHalf.Start();

And this seems to get the work done, but it's VERY slow. Every iteration is slower than the previous one, and when I debug, the Thread view shows a growing list of Threads.

But I was under the impression that Threads terminated themselves upon completion? And yes, the threads do complete. The DoOperation() method is pretty much just a for loop.

So what am I not understanding here?

Upvotes: 4

Views: 7819

Answers (2)

bamblack
bamblack

Reputation: 3779

To explain pranitkothari's answer a little bit more and give a different example you can use

list.AsParallel().ForAll(delegate([ListContainingType] item) {
    // do stuff to a single item here (whatever is done in DoOperation() in your code
    // except applied to a single item rather than several)
});

For instance, if I had a list string, it would be

List<String> list = new List<String>();
list.AsParallel().ForAll(delegate(String item) {
    // do stuff to a single item here (whatever is done in DoOperation() in your code
    // except applied to a single item rather than several)
});

This will let you perform an operation for each item in the list on a separate thread. It's simpler in that it handles all the "multi-threadedness" for you.

This is a good post that explains one of the differences in them

Upvotes: 2

Pranit Kothari
Pranit Kothari

Reputation: 9841

Try Parallel.For It will save lot of work.

Upvotes: 5

Related Questions