我正在尝试控制一台测试设备,并且我需要正确确定与它通信的顺序。
首先我打电话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;
}