本文介绍了串行端口和AutoResetEvent问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人

我有一个通讯类,它确实使用 SerialPort 进行通讯.我的第一个实现对端口进行了轮询,并且非常高效.因为我讨厌投票,所以我试图替换它.

我的想法:
-我迷上了 SerialPort.DataReceived . DataReceived 将从 SerialPort 线程中调用
-我的 DataReceived 检查条件,并将 AutoResetEvent 设置为发出信号,表明条件是否符合条件
-主线程使用 AutoResetEvent.WaitOne ()等待.

问题:
即使 DataReceived 发出 AutoResetEvent 信号,主线程也会冻结.

提前谢谢.
问候


代码片段:

Dear all

I have a communication class which does use SerialPort to communicate. My first implementation polled the port and was very efficient. Because I hate polling I tried to replace it.

My idea:
- I hook into SerialPort.DataReceived. DataReceived will be called from a the SerialPort thread
- My DataReceived checks the condition and set an AutoResetEvent to signaled if the condition meats the criterion
- The main thread waits using AutoResetEvent.WaitOne().

Problem:
Even while DataReceived signales AutoResetEvent, the main thread freezes.

Thanks in advance.
Regards


code fragments:

class CommunicationDeviceSerialPort : CommunicationDevice
{
  System.IO.Ports.SerialPort  serialPort  = new System.IO.Ports.SerialPort();
  AutoResetEvent              recSynchObj = new AutoResetEvent(false)
	
  // Hook for SerialPort.DataReceived. Called by the SerialPort receiver thread
  private void SerialDataReceivedEvent(object sender, SerialDataReceivedEventArgs e)
  {
    // Acoording to MSN docu, this will be called from a background thread


    // read in pending SerialPort data into deviceBuffer
    ... deviceBuffer

    // Check condition
    if (deviceBuffer meats my condition)
       recSynchObj.Set();
  }

  // Communicate will be called from the main thread 
  public int Communicate(String Command, int TimeoutMS, out Data)
  {
    // Some Cleanup
    ...

    // Send the command
    serialPort.Write(Command);

    // Ininite timeou for tests
    bool xSignaled= recSynchObj.WaitOne();  

    //************************************
    //****It never comes out of WaitOne one line above. Why???*****
    //************************************

    if (xSignaled)
    {
        // Read data from devicebuffer
        ...
    }

    // With Progress in final version
    /*
    while(true)
    {
      bool xSignaled= recSynchObj.WaitOne(250);
      if (xSignaled)
      {
        // Read data from devicebuffer
        ...
        break;
      }
      // ShowProgress();
      // CheckTimeout()
    }
    */
  }
}





class FormMain
{
  CommunicationDevice commDevice= new CommunicationDeviceSerialPort();

  private void DoCommunicate
  {
    // Send somthing
    commDevice.Communicate(cmd, 2000, );	
  }	
}

推荐答案


这篇关于串行端口和AutoResetEvent问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 04:11