2013-06-02 30 views
0

我正在尋找一個概念如何實現以下內容: 我有4個設備通過RS232連接到PC,我想創建一些控制應用程序。我已經爲處理通信和錯誤處理的4個不同設備創建了類。C#使用線程等待多個條件

在主線程中,我現在想創建一些初始化序列。例如一個控制參數是溫度。所以我設置了溫度,然後需要等待10分鐘直到達到溫度。到達時,我想設置電源的輸出電壓等等。有些參數需要並行控制(等待溫度進入可接受的窗口時,我還需要監測壓力是否在一定範圍內)。

所以,我夢想着這樣的事情,但對HOWTO不知道最好的意識到這一點:

Device1.setTemp(200); magic.Wait(獲取當前值的函數,包含最小/最大級別的對象,最大時間);

對於簡單的情況。但是我想,一旦我知道要走向哪個方向,我可以擴展它以允許監視多個值。

請給我一些好的方向。我已經看過線程,BackgroudWorkers等等。有很多不同的選項可用,但我不知道如何從一開始就以安全的方式創建它。

謝謝 thefloe

回答

1

您可以使用EventWaitHandles到你的線程同步內操作。閱讀更多here

static EventWaitHandle _go = new AutoResetEvent(false); 

static void Main(string[] args) 
{ 
    //Set the temperature 
    int Temp = 100; 
    int Voltage = 240; 

    Thread t1 = new Thread(() => SetTemperature(Temp)); 
    Thread t2 = new Thread(() => SetPowerVoltage(Votage)); 
    Thread t3 = new Thread(() => SomeOtherImportantWork()); //Which can go on in parallel 
    t1.Start(); 
    t2.Start(); 
    t3.Start(); 
    .... 
    .... 

    //you can wait or do other operations 
} 

//Logic to set the temperature 
static void SetTemperature(int temperature) 
{ 
    Console.WriteLine("Setting temperature"); 

    //Do your stuff  

    //Signal your other thread 
    _go.Set(); 

} 


static void SetPowerVoltage(int voltage)   
{ 
    //Wait for the temperature to be set 
    Console.WriteLine ("Waiting..."); 
    _go.WaitOne(); 


    //This will begin execution once the temp thread signals 
    //Do your stuff to set voltage 

} 

static void SomeOtherImportantWork()   
{ 
    //Do Important work 
} 
+0

非常感謝。我確信有一個簡單的方法來做到這一點。這正是我期待的;) – thefloe