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;
}
4

2 回答 2

1

与其反复调用 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;
}

如果不了解做什么ReadDataProcessIncomingTrace()做什么,就不可能具体知道为什么您的代码会冻结。

于 2013-05-09T14:50:07.093 回答
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();
}
于 2013-05-09T14:49:33.153 回答