Thread queues for dummies

后端 未结 8 1542
终归单人心
终归单人心 2021-02-06 11:59

I have what I assume is a pretty common threading scenario:

  • I have 100 identical jobs to complete
  • All jobs are independent of each other
  • I want t
8条回答
  •  再見小時候
    2021-02-06 12:13

    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();
    }
    

提交回复
热议问题