2010-04-23 7 views
11

C#을 알고 있지만 시그널링과 같은 몇 가지 기본 개념을 이해하는 데 어려움이 있습니다.스레드 신호 기초

나는 운이 없어도 몇 시간을 보냈다. 일부 예제 또는 실제 간단한 시나리오가이를 이해하는 데 도움이 될 수 있습니다.

답변

20

다음은 사용자를 위해 만들어진 콘솔 응용 프로그램 예제입니다. 좋은 실제 시나리오는 아니지만 쓰레드 시그널링의 사용법이 있습니다.

using System; 
using System.Threading; 

class Program 
{ 
    static void Main() 
    { 
     bool isCompleted = false; 
     int diceRollResult = 0; 

     // AutoResetEvent is one type of the WaitHandle that you can use for signaling purpose. 
     AutoResetEvent waitHandle = new AutoResetEvent(false); 

     Thread thread = new Thread(delegate() { 
      Random random = new Random(); 
      int numberOfTimesToLoop = random.Next(1, 10); 

      for (int i = 0; i < numberOfTimesToLoop - 1; i++) { 
       diceRollResult = random.Next(1, 6); 

       // Signal the waiting thread so that it knows the result is ready. 
       waitHandle.Set(); 

       // Sleep so that the waiting thread have enough time to get the result properly - no race condition. 
       Thread.Sleep(1000); 
      } 

      diceRollResult = random.Next(1, 6); 
      isCompleted = true; 

      // Signal the waiting thread so that it knows the result is ready. 
      waitHandle.Set(); 
     }); 

     thread.Start(); 

     while (!isCompleted) { 
      // Wait for signal from the dice rolling thread. 
      waitHandle.WaitOne(); 
      Console.WriteLine("Dice roll result: {0}", diceRollResult); 
     } 

     Console.Write("Dice roll completed. Press any key to quit..."); 
     Console.ReadKey(true); 
    } 
} 
+0

감사합니다. 늦은 응답으로 죄송합니다. Amry (어제 사망 한 비디오 카드, 오늘 새 동영상을 구입했습니다). 나는 곧바로 실행할 것이다. – Marcote

3

꽤 큰 영역으로 명확한 포인터를 제공합니다.

신호와 같은 개념을 이해하려면 Thread Synchronization에있는이 링크를 시작하는 것이 좋습니다. 그것도 예제가 있습니다. 그런 다음 특정 유형의 .net 유형으로 드릴려고 할 수 있습니다. 프로세스 내 또는 프로세스 내 스레드간에 신호를 보내십시오.

4

간단히 말해서 작동 방식.

  1. AutoResetEvent waitHandle = new AutoResetEvent(false);

    --- 거짓은 waitHandle.WaitOne이()는 스레드를 중지 호출되는 경우 그 대기 핸들이 unsignaled 있음을 의미합니다. waitHandle.Set();

waitHandle.WaitOne(); 대기를 추가 완료 할 때

  • 당신이 완료하는 또 다른 이벤트를 대기하는 스레드는 말에 완료 될 필요가있는 스레드에서 waitHandle.WaitOne();

  • 를 추가 신호를 위해

    waitHandle.Set(); 신호 완료.