如何关闭子线程?征集析构函数与多线程的讨论!

下面的代码是可以执行,大家都来说说为什么这个程序不会自动退出?
也就是说mian函数执行完毕后,为什么.net不会释放ThreadEx对象?

using  System;
using  System.Threading;

public   class  ThreadEx : IDisposable {    
    
private Thread thread;
    
private volatile bool bExit;
    
public ThreadEx(){
        Console.WriteLine(
"ThreadEx output");
        bExit 
= false;
        thread 
= new Thread(OnThread);
        thread.Start();
    }


    
~ThreadEx(){
        Console.WriteLine(
"~ThreadEx output");
        bExit 
= true;
    }


    
private void OnThread(){
        
while(true){
            
if(bExit){
                
break;
            }

            Console.WriteLine(
"Thread output");
            Thread.Sleep(
1000);
        }

        Console.WriteLine(
"Thread exit");
    }


    
private void Close(){
        bExit 
= true;
    }


    
public void Dispose() {
        
// TODO:  添加 ThreadEx.Dispose 实现
        Console.WriteLine("~Dispose output");
        bExit 
= true;
    }


    
static void Main(){
        ThreadEx threadEx 
= new ThreadEx();
    }

}

你可能感兴趣的:(如何关闭子线程?征集析构函数与多线程的讨论!)