Here's the scenario - I have a C# application that reads from a COM port. Most of the time I use devices with a serial adapter and on a machine with a serial ports. However, machines with serial ports are increasingly difficult to come by so I have started using machines with a USB/Serial connection.
In some cases, the C# code that I have will work just fine with a "true" serial connection but fail with a USB/serial connection. The data comes in fragmented with the first part of the data coming in (like maybe the first 1 or 2 characters) and nothing else.
I'm using something basic like comport.ReadExisting() to pick up the data from the port. Is this part of the problem? Are there other methods that would guarantee that all the data would be read in a single string?
Finall开发者_如何学编程y, I want to add that I've already played around with some of the USB/serial settings in device manager AND the data comes in fine when using good, ole' hyperterminal . . . so it has to be something in the code.
With USB-serial converters, you MUST set your receive timeout, because the data can sit in the USB device for a long time where Windows doesn't know about it. Real serial ports hold data in the 16550 FIFO where the Windows driver can see it.
Most of the times you would want to use the SerialPort.DataReceived event ( http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx ).
This requires you to combine the chunks of data manually since you can receive parts of your string, but once you detect the boundary of a single 'record' you can fire of processing that record while letting the IO receive more events.
This allows some asynchronous IO which doesn't block your threads, and thus allows more efficient handling of the data in general. If it helps in your specific situation I don't know, but it has helped me in the past dealing with data reading issues, low speeds, thread pooling, and lock-ups.
精彩评论