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();
}
ThreadPool.QueueUserWorkItem
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#
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);
The answers and comments here may seem a bit divided, this is because the first thing to do here is to check if your LongRunningMethod()
is suited for the Threadpool. If it is then using the ThreadPool is the best choice (low overhead, some rudimentary loadbalancing).
Otherwise, use Thread and ThreadStart:
ThreadStart starter = new ThreadStart(LongRun);
for (int i = 1; i <= 10; i++) // 10 threads are intended, note the i=1
{
Thread t = new Thread(starter);
t.Start();
}
Note 1: that there also exists a ParameterizedThreadStart class.
Note 2: You can't scale this to i < 100 or something, you need to keep a lid on the max number of threads. The pool already does that.
From MSDN:
There are several scenarios in which it is appropriate to create and manage your own threads instead of using thread pool threads:
Note that MSDN does not say what a 'long period of time' is. I'll take a stab at it and say that when your task takes >= 0.5 second you might start looking at separate threads. The overhead of creating a Thread becomes insignificant. But it depends on a lot of factors.
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();
}