What is the best way to launch 10 threads like in a for loop for a process intensive method. A code example would be very helpful.
for (int i = 0; i<=10; i++) //10 threads are intended.
{
LongRunningMethod();
}
What is the best way to launch 10 threads like in a for loop for a process intensive method. A code example would be very helpful.
for (int i = 0; i<=10; i++) //10 threads are intended.
{
LongRunningMethod();
}
Use Action as a delegate to create a new thread for each long running method call.
Action newThread = new Action(LongRunningMethod);
// Call Async which is a new thread
newThread.BeginInvoke(null, null);
Action with no template is only in .NET 3.5, for .NET 2.0 you have to declare a delegate
public delegate void NoParametersMethod();
NoParametersMethodnewThread = new NoParametersMethod(LongRunningMethod);
// Call Async which is a new thread
newThread.BeginInvoke(null, null);
Or if you don't want to use the thread pool, just create and start a new thread.
new Thread( delegate() { LongRunningMethod(); } ).Start();
As mentioned in the other answers, you can use ThreadPool.QueueUserWorkItem to schedule your job on a thread in the thread pool or create a new explicit Thread instance for that work. You can read more about the various ways to create threads at the MSDN Threading Tutorial.
Which approach you use can have certain implications on the performance and behavior of your app and the CLR. For more details, read When to use thread pool in C#
Something simple like this ...
var threads = new List<Thread>();
var numThreads = 10;
for( int i = 0; i < numThreads; i++ )
{
threads.Add( new Thread( () => DoWork() ) );
threads[i].Name = i.ToString();
threads[i].Start();
}