using System;
using System.Threading;public class Worker
{
    // This method will be called when the thread is started.
    public void DoWork()
    {
        while (!_shouldStop)
        {
            //进行某个操作,当完成了,就立即通知主线程,所有的子线程就应该结束。
            //Console.WriteLine("worker thread: working...");
            ...
        }
        Console.WriteLine("worker thread: terminating gracefully.");
    }
    public void RequestStop()
    {
        _shouldStop = true;
    }
    // Volatile is used as hint to the compiler that this data
    // member will be accessed by multiple threads.
    private volatile bool _shouldStop;
}public class WorkerThreadExample
{
    static void Main()
    {
        // Create the thread object. This does not start the thread.
        Worker workerObject = new Worker();
        Thread[] workerTheads=new Thread[10];
        for(int i=0;i<10;i++)
         {
            workerThread[i] = new Thread(workerObject.DoWork);
        
            // Start the worker thread.
            workerThread.Start();
        }
    }
}
我定义了10条子线程,即workerTheads,但他们在子线程里面怎么通知主线程把所有子线程都终止?

解决方案 »

  1.   

    _shouldStop = true;
    这个最简单,你要在主线程里结束子线程,
    要么主线程必须要有一个监视循环,
    要么设置一个事件,子线程调用这个事件
      

  2.   

    启动线程:
    ThreadStart thdStart = new ThreadStart(DoWork);
                thd = new Thread(thdStart);
                thd.Start();
    在子线程中关闭线程:
       thd.Abort();
      

  3.   

    本人已经解决:多线程之间往往直接alort()并不会直接把多线程结束,因此在多线程要做的方法里面放一个判断,以后只要直接把那个判断改下,比直接用abort效率高!