0

EDIT: I'm developing with .NET 3.5.

i've a Procedure that DoSomething. I've to launch it for X times. I would like to use thread .. but i want to use a maximum of 5 thread per time. So, i can write something like:

for i=0 to TimesToDo -1
       Dim t as new Thread = new Thread(Addressof MyProcedure)
       t.Start()

      if TotalThread > 5 then Wait()
next i

Ok this is 'pseudo code'. Is it possible in .NET ? Some other questions are: how can i get the number of my thread running ? Is it possible to get the 'signal' of ending thread ?

Thanks

stighy
  • 7,260
  • 25
  • 97
  • 157
  • check this post http://stackoverflow.com/questions/444627/c-thread-pool-limiting-threads – Samich Sep 18 '11 at 19:16
  • In regards to waiting, it's worth mentioning `Thread.Join` (http://msdn.microsoft.com/en-us/library/95hbf2ta.aspx), which *"blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping."* Unfortunately this doesn't apply directly to your problem, since waiting for each thread would severely limit parallelism. – Rob Sep 18 '11 at 19:27
  • The threadpool manager already does that. Preferred since it doesn't just pick 5, it picks a number that works well on the machine, matching the number of cpu cores. – Hans Passant Sep 18 '11 at 20:14

2 Answers2

4

Assuming .Net 4.0, you can use Parallel.For (C# code):

var parallelOptions = new ParallelOptions {MaxDegreeOfParallelism=5};

Parallel.For(0, TimesToDo -1, parallelOptions, DoSomething);
Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
3

Are all of your threads doing the same work? If so, I would suggest creating 5 threads which all read from the same work queue - a BlockingCollection<T> if you're using .NET 4 - and then you would add items to that queue. That will avoid the cost of creating threads when you don't really need to, and put a natural limit of 5 threads processing your data at a time.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194