我正在尝试生成一个线程来处理应该少于3秒的DoWork任务。在DoWork内部,耗时15秒。我想中止DoWork,然后将控件转移回主线程。我已将代码复制如下,并且无法正常工作。它仍然可以完成DoWork,然后将控制权转回主线程,而不是中止DoWork。我究竟做错了什么?

class Class1
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    ///

    private static System.Threading.ManualResetEvent[] resetEvents;

    [STAThread]
    static void Main(string[] args)
    {
        resetEvents = new ManualResetEvent[1];

        int i = 0;

        resetEvents[i] = new ManualResetEvent(false);
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork),(object)i);


        Thread.CurrentThread.Name = "main thread";

        Console.WriteLine("[{0}] waiting in the main method", Thread.CurrentThread.Name);

        DateTime start = DateTime.Now;
        DateTime end ;
        TimeSpan span = DateTime.Now.Subtract(start);


        //abort dowork method if it takes more than 3 seconds
        //and transfer control to the main thread.
        do
        {
            if (span.Seconds < 3)
                WaitHandle.WaitAll(resetEvents);
            else
                resetEvents[0].Set();


            end = DateTime.Now;
            span = end.Subtract(start);
        }while (span.Seconds < 2);



        Console.WriteLine(span.Seconds);


        Console.WriteLine("[{0}] all done in the main method",Thread.CurrentThread.Name);

        Console.ReadLine();
    }

    static void DoWork(object o)
    {
        int index = (int)o;

        Thread.CurrentThread.Name = "do work thread";

        //simulate heavy duty work.
        Thread.Sleep(15000);

        //work is done..
        resetEvents[index].Set();

        Console.WriteLine("[{0}] do work finished",Thread.CurrentThread.Name);
    }
}

最佳答案

所有pooled threads都是后台线程,这意味着它们在应用程序的前台线程结束时自动终止。

我更改了循环并删除了resetEvents。

     //abort dowork method if it takes more than 3 seconds
     //and transfer control to the main thread.
     bool keepwaiting = true;
     while (keepwaiting)
     {
        if (span.Seconds > 3)
        {
           keepwaiting = false;
        }

        end = DateTime.Now;
        span = end.Subtract(start);
     }

关于c# - .NET 1.0 ThreadPool问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2962519/

10-12 03:44