2010-06-03 2 views
2

스레드를 생성하여 3 초 미만의 DoWork 작업을 처리하려고합니다. DoWork 내부에서 15 초가 걸립니다. 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를 실제로 사용하는 경우, 잘못하고있는 것은 8 년 된 소프트웨어를 사용하는 것입니다. 왜 .NET 1.1 SP1을 실행하지 않으십니까? –

+0

.net의 어떤 버전이 사용 중인지에 따라 다릅니다. –

답변

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

은 단일 스레드 아파트입니다. 멀티 스레드 아파트 인 [MTAThread]을 시도하십시오.

+0

[MTAThread] 시도했지만 작동하지 않았다. DoWork 메소드를 여전히 중단 할 수는 없습니다. –