be notified when all background threadpool threads are finished

后端 未结 7 1818
星月不相逢
星月不相逢 2020-12-16 01:37

I have a scenario when I start 3..10 threads with ThreadPool. Each thread does its job and returns to the ThreadPool. What are possible options to be notified in main thread

7条回答
  •  囚心锁ツ
    2020-12-16 02:33

    Marc's solution is best if you just want to know when all the jobs are finished, and don't need finer info than that (as seems to be your case).

    If you wanted some thread to spawn jobs, and some other thread to to receive the notifications, you could use WaitHandle. The code is much longer.

        int length = 10;
        ManualResetEvent[] waits = new ManualResetEvent[length];
        for ( int i = 0; i < length; i++ ) {
            waits[i] = new ManualResetEvent( false );
            ThreadPool.QueueUserWorkItem( (obj) => {
                try {
    
                } finally {
                    waits[i].Set();
                }
            } );
        }
    
        for ( int i = 0; i < length; i++ ) {
            if ( !waits[i].WaitOne() )
                break;
        }
    

    The WaitOne method, as written, always returns true, but I have written it like that to make you remember that some overloads take a Timeout as an argument.

提交回复
热议问题