System.IO.Ports.SerialPort and Multithreading

后端 未结 4 671
清酒与你
清酒与你 2021-02-02 04:42

I have some SerialPort code that constantly needs to read data from a serial interface (for example COM1). But this seems to be very CPU intensive and if the user moves the wind

4条回答
  •  醉话见心
    2021-02-02 05:18

    I am surprised no one caught this. The SerialPort class utilizes its own thread when using the DataReceived event. This means that if the subscriber, for example, is accessing any Form elements, then it must be done so with either an Invoke, or BeginInvoke method(s). Otherwise, you end up with a cross thread operation. In older versions of .net, this would go along unnoticed with unpredictable behaviour (depending on the CPU cores in the PC) and in later versions, should raise an exception.

提交回复
热议问题