4

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?

Christofer Ohlsson
  • 3,097
  • 4
  • 39
  • 56

2 Answers2

5

Try Parallel.For It will save lot of work.

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137
2

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

Community
  • 1
  • 1
Ben Black
  • 3,751
  • 2
  • 25
  • 43
  • No luck so far with this approach. Lots of squiggly red lines. It says the type for the argument to the ForAll() call cannot be inferred. Is it because it is a custom object and not a primitive? – Christofer Ohlsson Jun 08 '14 at 21:59
  • That shouldn't matter, as long as you replace `[ListContainingType]` with the type that is contained in the list, then it should work. – Ben Black Jun 09 '14 at 13:23
  • I did that. But don't have the code available to me at the moment. Will have a look later on. Maybe I made some other silly mistake. – Christofer Ohlsson Jun 09 '14 at 13:42
  • Gotcha, when you get it, go ahead and update your question with what you've tried so we can see what exactly is happening. – Ben Black Jun 09 '14 at 13:44