开发者

.NET Serial Port DataReceived (On/Off)

I'm using the .NET 4 Serial Port Class and a DataReceived handler.

In the DataReceive handler, I remove the handler from the serial port, process the data, and re-add the handler at the end of the function.

try
{
  serial_port.datareceived -= new serialdatareceivedeventhandler(ondatareceived);

  // readline and process data
}
catch (exception ex)
{
}
finally
{
  serial_port.datareceived += new serialdatareceivedeventhandler(开发者_如何转开发ondatareceived);
}

What are the ramifications, if any, of this usage? It appears to work just fine, though I haven't tested it long term. Should I look into a different methodology? Please give a simple code sample/outline if possible. Thank you.


I personally would not remove the handler on every DataReceived Event, it is unneccessary. If you don't get notification of incoming data there is always the possibility of overrunning the existing buffer and loosing information.

I would use something similar to the Microsoft Example:

From above MSDN article:

 private static void DataReceivedHandler( object sender, SerialDataReceivedEventArgs e)
 {
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
    Console.WriteLine("Data Received:");
    Console.Write(indata);
  }


If you're worried about Reentrancy, use a lock or mutex:

lock(lockobj)
{
    /*Read data from the port here.*/
}

Unsubscribing from the event isn't successful to prevent reentrancy because, due to preemptive scheduling (as opposed to cooperative multi-threading or something similar), your code could be preempted just after entering the method (or even before that) before you get a chance to unsubscribe, and more data arrives, triggering the mechanism again.

In actuality, the documentation says explicitly,

Only one event handler can execute at a time.


Regarding this code:

catch (exception ex)
{
}

Never, ever, ever, ever, ever, ever, ever, ever, ever, ever write code like that.

It's like removing the smoke detectors in your children's bed rooms.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜