考慮我在C#中有一個事件偵聽器,它等待來自串行端口的數據,這些數據一旦通過設置某個狀態捕獲就會返回。在主循環中,我研究了這種狀態,並基於此決定下一步該做什麼。在主線程的睡眠模式下處理從事件處理程序發送的數據C#
爲此,我首先將命令寫入串行端口,並使用Thread.Sleep方法等待輸出。在主線程仍處於睡眠模式時,事件偵聽器已經發送了數據,並且沒有任何事情可以處理這種情況。
任何人都可以請告訴我在這種情況下會有怎樣的結果以及如何預防它?
的代碼會像
bool status = false;
//main thread
private void Main()
{
//some Code
serialPort.Write("something");
//Wait for 10 sec
Thread.Sleep(10000);
while(status == false)
{
// do something else
}
}
//Ignore the syntax, this is just to make people understand
public void OndataReceived(object sender, EventArg arg)
{
//Function that recieve the data
Receive();
//change status to true
status = true;
return;
}
看一看手冊 - 和的AutoResetEvent – Dawnkeeper
創建自定義事件,從'OndataReceived'方法內火了,做在我看來 –