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 开发者_如何学Python= 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
Assuming .Net 4.0, you can use Parallel.For
(C# code):
var parallelOptions = new ParallelOptions {MaxDegreeOfParallelism=5};
Parallel.For(0, TimesToDo -1, parallelOptions, DoSomething);
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.
精彩评论