2010-07-12 4 views
4

이 코드에서 AutoResetEvent 및 bool 변수를 사용하여 스레드를 일시 중지/다시 시작하려고합니다. 블로킹이 == true 일 때마다 매번 테스트를 중단 할 수 있습니까 (For 루프의 Work())? "차단 된"변수의 테스트는 또한 잠금이 필요하며 시간이 많이 소요됩니다.스레드를 일시 중지/다시 시작 AutoResetEvent

class MyClass 
    { 
     AutoResetEvent wait_handle = new AutoResetEvent(); 
     bool blocked = false; 

     void Start() 
     { 
      Thread thread = new Thread(Work); 
      thread.Start(); 
     } 

     void Pause() 
     { 
      blocked = true; 
     } 

     void Resume() 
     { 
      blocked = false; 
      wait_handle.Set(); 
     } 

     private void Work() 
     { 
      for(int i = 0; i < 1000000; i++) 
      { 
       if(blocked) 
        wait_handle.WaitOne(); 

       Console.WriteLine(i); 
      } 
     } 
    } 

답변

9

예, 수행중인 테스트는 ManualResetEvent으로 피할 수 있습니다.

ManualResetEvent은 사용자가 이전에 가지고 있던 AutoResetEvent과 달리 스레드가 통과 할 때 자동으로 재설정하지 않습니다. 즉, 루프에서 작업 할 수 있도록 설정하고 일시 중지로 재설정 할 수 있습니다.

class MyClass 
{ 
    // set the reset event to be signalled initially, thus allowing work until pause is called. 

    ManualResetEvent wait_handle = new ManualResetEvent (true); 

    void Start() 
    { 
     Thread thread = new Thread(Work); 
     thread.Start(); 
    } 

    void Pause() 
    { 

     wait_handle.Reset(); 
    } 

    void Resume() 
    { 
     wait_handle.Set(); 
    } 

    private void Work() 
    { 
     for(int i = 0; i < 1000000; i++) 
     { 
      // as long as this wait handle is set, this loop will execute. 
      // as soon as it is reset, the loop will stop executing and block here. 
      wait_handle.WaitOne(); 

      Console.WriteLine(i); 
     } 
    } 
} 
관련 문제