日期:2014-05-18  浏览次数:21778 次

线程池高手请进!如何停止线程池(ThreadPool)中的线程!
最近写一小程序,使用到了线程池(ThreadPool)。程序界面上有个停止按钮,点下停止按钮后,我需要停止线程池中的所有工作线程不知如何操作,请高手指教!。
  现在我代码结构是这样的,两个类:WorkManager,WorkThread 第一个类是用来产生工作线程和控制工作线程的。现在想停止线程池中的线程却不知道怎么操作,尝试过工作线程注册管理线程的事件,由事件通知工作线程内部使用Thread.CurrentThread.Abort();进行停止也不行。。。真没辙了。



------解决方案--------------------
abort不是管理线程的好办法
http://topic.csdn.net/u/20120113/11/3fd689ca-4ddb-4c74-a746-06ff73dc7406.html
------解决方案--------------------
在.NET4.0中CancellationTokenSource可以实现。
------解决方案--------------------
C# code
   private static void CancellingAWorkItem() {
        CancellationTokenSource cts = new CancellationTokenSource();

        // Pass the CancellationToken and the number-to-count-to into the operation
        ThreadPool.QueueUserWorkItem(o => Count(cts.Token, 1000));

        Console.WriteLine("Press <Enter> to cancel the operation.");
        Console.ReadLine();
        cts.Cancel();  // If Count returned already, Cancel has no effect on it
        // Cancel returns immediately, and the method continues running here...

        Console.ReadLine();  // For testing purposes
    }

    private static void Count(CancellationToken token, Int32 countTo) {
        for (Int32 count = 0; count < countTo; count++) {
            if (token.IsCancellationRequested) {
                Console.WriteLine("Count is cancelled");
                break; // Exit the loop to stop the operation
            }

            Console.WriteLine(count);
            Thread.Sleep(200);   // For demo, waste some time
        }
        Console.WriteLine("Count is done");
    }

------解决方案--------------------
探讨
C# code
private static void CancellingAWorkItem() {
CancellationTokenSource cts = new CancellationTokenSource();

// Pass the CancellationToken and the number-to-count-to into t……