Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 958
Christofer Ohlsson Avatar asked Mar 19 '23 09:03

Christofer Ohlsson


2 Answers

Try Parallel.For It will save lot of work.

like image 100
Pranit Kothari Avatar answered Mar 27 '23 15:03

Pranit Kothari


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

like image 20
Ben Black Avatar answered Mar 27 '23 14:03

Ben Black