2013-05-09 38 views
0

我試圖控制一塊測試設備,並且我需要確定如何與其進行通信的順序正確。爲什麼這個線程永無止境?

首先我打電話StartGettingTraceData()。然後在將來的某個時間,我會呼叫StopGettingTraceData()嘗試結束GetTraceData()函數,而不是重新啓動它自己。但是,永遠不會發生。其實我從來沒有去過線DoneTraces.Set()所以就行bool timedOut = !DoneTraces.WaitOne(10000)timedOut總是如此;

private static AutoResetEvent DoneTraces = new AutoResetEvent(false); 

private void GetTraceData() 
{ 
    byte[] receivedbytes = new byte[1]; 
    if (Connection.ReadData(receivedbytes) && receivedbytes[0] == 192) 
     ProcessIncomingTrace(); 

    Thread.Sleep(100); 

    if (RunTraceQueryWorker) 
     new Thread(GetTraceData).Start(); 
    else 
    { 
     Thread.Sleep(200); 
     DoneTraces.Set(); 
    } 
} 

private void StartGettingTraceData() 
{ 
    RunTraceQueryWorker = true; 
    new Thread(GetTraceData).Start(); 
} 

private bool StopGettingTraceData() 
{ 
    RunTraceQueryWorker = false; 
    bool timedOut = !DoneTraces.WaitOne(10000); 
    return timedOut; 
} 

對發生了什麼有什麼想法?

編輯:

這是我Connection.ReadData(...)函數。順便說一句,這是一個串行連接。

public bool ReadData(byte[] responseBytes) 
{ 
    int bytesExpected = responseBytes.Length, offset = 0, bytesRead; 
    while (bytesExpected > 0 && (bytesRead = MySerialPort.Read(responseBytes, offset, bytesExpected)) > 0) 
    { 
     offset += bytesRead; 
     bytesExpected -= bytesRead; 
    } 
    return bytesExpected == 0; 
} 
+1

線程很貴,所以你不應該遞歸地創建它們。有這麼多的線程(做'睡眠()')可能也是你不停的問題。 – 2013-05-09 14:46:46

+0

您是否嘗試過使用DataReceived事件處理程序?我昨天看了這本手冊,看起來非常直截了當,除了可能的不同反應之外。 – dbasnett 2013-05-09 15:05:20

回答

1

不是recusively再打電話給GetTraceData,你應該使用while循環看着你的病情是這樣的:

private static AutoResetEvent DoneTraces = new AutoResetEvent(false); 

private void GetTraceData() 
{ 
    do 
{ 
    byte[] receivedbytes = new byte[1]; 
    if (Connection.ReadData(receivedbytes) && receivedbytes[0] == 192) 
     ProcessIncomingTrace(); 

    Thread.Sleep(100); 
} 
while (RunTraceQueryWorker) 

Thread.Sleep(200); 
DoneTraces.Set(); 

} 

private void StartGettingTraceData() 
{ 
    RunTraceQueryWorker = true; 
    new Thread(GetTraceData).Start(); 
} 

private bool StopGettingTraceData() 
{ 
    RunTraceQueryWorker = false; 
    bool timedOut = !DoneTraces.WaitOne(10000); 
    return timedOut; 
} 

這是不可能知道具體是爲什麼你的代碼凍結不理解什麼ReadData & ProcessIncomingTrace()做。

+0

你說得對。當我註釋掉這兩行代碼時,情況正常。我必須有其他問題。 – 2013-05-09 14:58:12

+0

如果你在ReadData()調用中放置一個斷點,你有沒有看到它返回? – Chris 2013-05-09 15:03:29

+0

我決定使用與你非常相似的代碼(while while循環)。解決我的問題,我不得不使用'ProcessIncomingTrace()'函數。現在就像魅力一樣。 – 2013-05-09 19:48:28

0

那麼,很有可能ReadData呼叫被阻止。順便說一句,你用所有這些遞歸線程讓自己變得很難......你不能只用一個循環嗎?

private void GetTraceData() 
{ 
    byte[] receivedbytes = new byte[1]; 

    while(RunTraceQueryWorker) 
    { 
     if(Connection.ReadData(receivedbytes) && receivedbytes[0] == 192) 
     { 
      ProcessIncomingTrace(); 
     } 
     Sleep(100); 
    } 

    Thread.Sleep(200); 
    DoneTraces.Set(); 
}