C#关闭所有线程的窗体连接



我有一段简单的代码:

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);
}

Face form在程序启动时创建,并有一些控件,所以当我使用start((和Stop((方法时,一切都很好(所有线程正常连接(。

但当我按下"X"窗体按钮时,程序堆栈显示为"等待线程加入"。为什么?我错过了什么?

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

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

最新更新