I am writing C# WPF code to spy on a serial port (debugging tool). I am creating two virtual ports connected as null modem with com0com (app) and using my code to read off one port and immediately send out the other port, and vice versa:
HOST <--> Virtual COM <--> C# spy app <--> Real COM <--> TARGET
For this, I have created one class to manage a SerialPort object that creates an DataReceived event. In this implementation, I would have two instances of this class, one to manage HOST communication and the other for the target. The UI will only parse and display data from these two classes.
The problem: serial ports run on different threads than UI... and I have two of them trying to update the same UI.
My approach to this is to create a public List<T>
where T could be a struct { byte[] data; Direction direction}
to which each event handler would append its data, while the UI could parse this data. Event handlers would do List.Add(), while UI would do List.RemoveAt(0) while data exists. Data speed: 19200bps (1 byte every 0.5ms).
Questions: Can event handlers from two different serial ports interrupt each other and corrupt List data? Would using a List object affect performance? Should I try with an array of struct and just keep track of indices?
Or should I do something completely differen开发者_运维问答t?
Can event handlers from two different serial ports interrupt each other and corrupt List data?
Absolutely, the DataReceived event is raised on a threadpool thread. You've got a three-ring circus going on here, two threads that can receive something at the same time, an UI thread that's reading the received data at the same time. Locking is required to protect the List<>.
精彩评论