I have what I assume is a pretty common threading scenario:
ThreadPool
might be the way to go. The SetMaxThreads
method would be able to restrict the number of threads which are being executed. However, this restricts the maximum number of threads for the process/AppDomain. I wouldn't suggest using SetMaxThreads
if the process is running as a service.
private static ManualResetEvent manual = new ManualResetEvent(false);
private static int count = 0;
public void RunJobs( List states )
{
ThreadPool.SetMaxThreads( 15, 15 );
foreach( var state in states )
{
Interlocked.Increment( count );
ThreadPool.QueueUserWorkItem( Job, state );
}
manual.WaitOne();
}
private static void Job( object state )
{
// run job
Interlocked.Decrement( count );
if( Interlocked.Read( count ) == 0 ) manual.Set();
}