Wait until all threads finished their work in ThreadPool

后端 未结 5 464
不知归路
不知归路 2020-12-09 10:28

i have this code:

var list = new List();
for(int i=0;i<10;i++) list.Add(i); 
for(int i=0;i<10;i++)
{
     ThreadPool.QueueUserWorkItem(
             


        
5条回答
  •  醉话见心
    2020-12-09 10:37

    The thread pool does not tell you when the thread has finished executing, so the work item must do it itself. I changed the code like this:

        var list = new List();
        ManualResetEvent[] handles = new ManualResetEvent[10];
        for (int i = 0; i < 10; i++) {
            list.Add(i);
            handles[i] = new ManualResetEvent(false);
        }
        for (int i = 0; i < 10; i++) {
            ThreadPool.QueueUserWorkItem(
             new WaitCallback(x =>
             {
                 Console.WriteLine(x);
                 handles[(int) x].Set();
             }), list[i]);
        }
    
        WaitHandle.WaitAll(handles);
    

提交回复
热议问题