C#怎样控制同时开出多个线程执行任务,等所有线程都执行完了再返回

拿一个 Array 装 Task,然后 Task.WaitAll
■网友
首先应该用Task了现在。
其次谁说foreach里面Join会让线程排队的,再仔细想想。
【C#怎样控制同时开出多个线程执行任务,等所有线程都执行完了再返回】 最后好烦这种伸手党问题啊。

■网友
foreach(thread) thread.Join(); 难道不可以么?
■网友
How to: Write a Simple Parallel.ForEach LoopParallel.ForEach internally executes the tasks, they will done asynchronously. OR...Task tasks = new Task;for (int i = beginId; i \u0026lt;= maxId; i += interval, counter++)tasks = new Task(worker.TestHandler, TaskCreationOptions.LongRunning);var continuation = Task.Factory.ContinueWhenAll( tasks, (antecedents) =\u0026gt; { LogInfo("All threads have loaded!"); });foreach (Task t in tasks) t.Start();LogInfo("All threads have been queued. Waiting to complete...");while (!continuation.IsCompleted)Thread.Sleep(1000);In the comments, I was told that I should avoid Thread.Sleep(), all right, let\u0026#39;s try this:1. you could wrap the parallel.foreach within a task and manually add your completedCallback()public Task DoWorkAsync(DoWorkCompletedCallback completedCallback){ return Task.Factory.StartNew( { Parallel.Foreach //call callback manually completedCallback(); });}2. Use ContinueWithTask.Factory.StartNew( { //do work } ).ContinueWith(completedCallback);3. you could assign callback in the caller, it\u0026#39;s the same as 2. Task newTask = Task.Factory.StartNew( { //do work});newTask.ContinueWith(onCompleted);4. consumer-publisher patternsProducer Consumer problemAssume you have a huge object hosting messages ConcurrentList\u0026lt;string\u0026gt;, task pushes a message \u0026#39;OnCompleted\u0026#39; to the object, on the other side, a listener subscribes the message, once a OnCompleted received, it will execute the continuation.
■网友
从容错性、易调试性、整机性能、用户体验的角度来说,线程控制用开关变量+Sleep其实更好。觉得Sleep 500ms时间太长的话,试试1~50ms。
■网友
t1.start();t2.start();t1.join();t2.join();If the thread has already terminated when Join is called, the method returns immediately.没感觉这样有什么问题,t1和t2没有任何关系啊
■网友
用WaitHandle.WaitAll
■网友
首先,while() + Sleep 当然是不高效的。其次,“等所有线程完成”说明是一个条件。所以可以使用条件变量。比如主线程等待条件变成n,N个线程各自执行完毕后对条件++。Thread.Join也可以啊,为什么叫一个线程一个线程排队呢?线程根本没有排队,执行完毕就消失了,只不过,主线程要阻塞等待那些Join的线程,这也不浪费CPU。不是不是啊, @赵劼


    推荐阅读