Create multiple threads and wait all of them to complete

前端 未结 8 1976
星月不相逢
星月不相逢 2020-12-02 15:13

How can I create multiple threads and wait for all of them to complete?

8条回答
  •  情话喂你
    2020-12-02 15:41

    Most proposed answers don't take into account a time-out interval, which is very important to prevent a possible deadlock. Next is my sample code. (Note that I'm primarily a Win32 developer, and that's how I'd do it there.)

    //'arrRunningThreads' = List
    
    //Wait for all threads
    const int knmsMaxWait = 3 * 1000;           //3 sec timeout
    int nmsBeginTicks = Environment.TickCount;
    foreach(Thread thrd in arrRunningThreads)
    {
        //See time left
        int nmsElapsed = Environment.TickCount - nmsBeginTicks;
        int nmsRemain = knmsMaxWait - nmsElapsed;
        if(nmsRemain < 0)
            nmsRemain = 0;
    
        //Then wait for thread to exit
        if(!thrd.Join(nmsRemain))
        {
            //It didn't exit in time, terminate it
            thrd.Abort();
    
            //Issue a debugger warning
            Debug.Assert(false, "Terminated thread");
        }
    }
    

提交回复
热议问题