C#表单关闭所有线程连接

时间:2015-07-02 06:27:33

标签: c# multithreading winforms

我有这段简单的代码:

private volaile bool working;
private volatile List<Thread> threads = new List<Thread>();
private volatile Form Face;

public void Start(int n) 
{
    working = true;
    for (int i = 0; i <= n; i++) 
    {
        Thread worker = new Thread(() =>
        {
            while(working) 
            {
                // do some work     
            }
        });
        threads.Add(worker);
        worker.Start();
    }
}

public void Stop() 
{
    if(working)
    {
        working = false;

        logger.Info("Waiting threads join");
        foreach (Thread worker in threads)
        {
            worker.Join();
        }
        logger.Info("Threads joined");
    }
}

private void Face_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    Face.Invoke(new Action(() => {Stop();}));
    System.Environment.Exit(0);
}

Faceform在programm start上创建并有一些控件,所以当我使用Start()和Stop()方法时,一切正常(所有线程都正常连接)。

但是当我按下&#34; X&#34;表单按钮,程序堆栈&#34;等待线程加入&#34;。为什么?我错过了什么?

1 个答案:

答案 0 :(得分:0)

Thread sample = new Thread(new ThreadStart(Thread1));
        sample.IsBackground= true;

尝试将线程设置为后台线程。