Dragouf
Dragouf

Reputation: 4734

Thread Management in C# .Net 4.5

I am trying to do some multithreads calculations but I'm having some trouble to manage each thread independently.

For instance, if one thread finishes its calculation faster than the others, how can I detect it and start a new thread for the next calculation without waiting for the whole process and all the other thread to complete their own task ?

I am using C# .net 4.5 by the way.

Thanks

Upvotes: 1

Views: 4713

Answers (2)

Imran Rizvi
Imran Rizvi

Reputation: 7438

Create TPL Task for each calculation, and start them, internally each task will be queued and will execute when threads get available, thus you don't have to bother about thread management, it will be handled internally.

if you want to limit maximum parallel task to execute at a time you can use Parallel.Invoke method and set MaxDegreeOfParallelism e.g.

Parallel.Invoke(
new ParallelOptions() { MaxDegreeOfParallelism = 3 }, 
() => Calculation1(), 
() => Calculation2(),
() => Calculation3(),
);

Parallel.Invoke takes an array of parameters and perform action on it to run them all in parallel, at the same time you can set MaxDegreeOfParallelism to set maximum number of calculations to be run at a time.

e.g.

I suppose you have same method (Calculate) but multiple parameters (Parameters) as input.

Parallel.ForEach(Parameters,new ParallelOptions() { MaxDegreeOfParallelism = 3 }, parameter=> Calculate(parameter));

Upvotes: 1

AlfredBr
AlfredBr

Reputation: 1351

Since you are using .NET4.5, why not just use the TPL - Task Parallel Library ? It does all that you are trying to do (task scheduling and management) and more.

http://msdn.microsoft.com/en-us/library/dd460717.aspx

From the site:

The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces in the .NET Framework 4. The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. In addition, the TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool, cancellation support, state management, and other low-level details. By using TPL, you can maximize the performance of your code while focusing on the work that your program is designed to accomplish.

Upvotes: 1

Related Questions