2010-04-23 64 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 2010-04-25 00:07:33

3

這是一個相當大的面積,我給你明確的指針。

對於理解像信號的概念,對Thread Synchronization這個鏈接將是一個良好的開端。它也有例子。然後,您可以深入瞭解基於你想一個進程內或跨流程等做..線程之間的信號有什麼具體的.NET類型..

4

這是簡單的工作方式。

  1. AutoResetEvent waitHandle = new AutoResetEvent(false); ---假意味着等待句柄是unsignaled如果waitHandle.WaitOne()被調用時,它將停止線程。

  2. 要等待另一個事件完成線程添加 waitHandle.WaitOne();

  3. 在一個需要結束線程,在年底的時候完成新建 waitHandle.Set();

waitHandle.WaitOne();等待用於信號

waitHandle.Set();信號完成。