2010-06-03 46 views
2

我正在尝试产生一个线程来照顾DoWork任务,该任务应该少于3秒。 DoWork内部需要15秒。我想中止DoWork并将控制权转交回主线程。我已经复制了代码,如下所示,但它不起作用。 DoWork不是终止DoWork,而是完成DoWork,然后将控制权转交回主线程。我究竟做错了什么?.NET 1.0 ThreadPool问题

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); 
    } 
} 
+0

如果你真的使用VS2002,那么你做错的一件事就是使用八年前的软件。你为什么不至少运行.NET 1.1 SP1? – 2010-06-03 00:16:39

+0

对于使用什么版本的.net,它不是我所能接受的。 – 2010-06-03 00:37:33

回答

1

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

我改变了你的循环,并删除了重置事件。

 //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); 
    } 
0

[STAThread]是单线公寓。尝试[MTAThread]这是多线程公寓。

+0

我试过[MTAThread]它没有工作。我仍然无法中止DoWork方法。 – 2010-06-03 00:41:27