C#.Net 4.0控制台应用程序 - 如何在所有线程完成之前保持活力?

dow*_*one 6 c# multithreading .net-4.0 console-application

可能重复:
C#:等待所有线程完成

我有一个控制台应用程序产生一些线程,然后退出.每个线程大约需要20秒才能完成.似乎控制台应用程序正在生成线程,然后在线程有机会完成之前退出.

如何告诉控制台应用程序在它生成的所有线程完成之前不要退出?

Joh*_*ert 6

是否为循环生成了线程?如果是这样,Parallel.ForEach将起作用:

ParallelOptions options = new ParallelOptions();
                    Parallel.ForEach(items, options, item=>
                    {
// Do Work here
                        }
                    });
Run Code Online (Sandbox Code Playgroud)


Tim*_*ker 6

你可以用一个CountDownEvent.

using System;
using System.Collections.Generic;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static CountdownEvent countdown;

        static void Main(string[] args)
        {
            countdown = new CountdownEvent(1);
            for (int i = 1; i < 5; i++)
            {
                countdown.AddCount(); //add a count for each (BEFORE starting thread .. Thanks, Brian!)
                //do stuff to start background thread
            }
            countdown.Signal(); //subtract your initial count
            countdown.Wait(); //wait until countdown reaches zero
            //done!
        }

        static void backgroundwork()
        {
            //work
            countdown.Signal(); //signal this thread's completion (subtract one from count)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我经常使用这种模式.它运作得很好.注意,`AddCount`应该在启动线程之前发生,否则会有一个非常微妙的错误,如果第一个线程在调用`AddCount`之前完成,则可能导致事件过早地发出信号. (2认同)