2010-06-03 72 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