我正在尝试控制一台测试设备,我需要对测试设备进行正确的测序。
首先我打电话给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;
}
答案 0 :(得分:1)
您应该使用while循环查看您的条件,而不是再次重复调用GetTraceData:
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()
做。
答案 1 :(得分: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();
}