【问题标题】:.NET 1.0 ThreadPool Question.NET 1.0 线程池问题
【发布时间】:2011-02-27 02:20:55
【问题描述】:

我正在尝试生成一个线程来处理 DoWork 任务,该任务应该花费不到 3 秒的时间。在 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);
    }
}

【问题讨论】:

  • 如果你真的在使用 VS2002,那么你做错的一件事就是使用了八年的软件。你为什么不至少运行 .NET 1.1 SP1?
  • 使用的 .net 版本不取决于我。

标签: c# multithreading .net-1.0


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    [STAThread] 是单线程单元。试试[MTAThread],它是多线程单元。

    【讨论】:

    • 我试过 [MTAThread] 没用。我仍然无法中止 DoWork 方法。
    猜你喜欢
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    相关资源
    最近更新 更多