开发者

SerialPort timeouts in standalone mode

I have a strange behaviour im my app.

I open a COM port to comunicate witha a device over Bluetooth. I do the following steps:

  1. Open the virtual COM port;
  2. Switch remote bluetooth to command mode;
  3. Perform few commands (eg. read remote device's serial number);
  4. Switch remote bluetooth to data amode;
  5. Send data to device;
  6. Read a byte of answer (ReadByte() from SerialPort class);

    The device works fine and answers immediately and everything is fine while I run my app in debug mode via visual studio.

But when I try to run it directly (without visual studio and adebugger attatched - but still compiled with "Debug" option) i get a timeout exception at step 6.

The bug is fully reproducible (no timeouts in Visual Studio, and every time without it).

Does anyone have any idea that could cause such behaviour ?

Here is the code from step 6

    private byte[] ReadResponse() {开发者_开发百科

        try {
            int bytes2Read = 6;
            do {
                this.buffer.Append((byte)ReadByte()); // <- there the timeout occurs

                if (this.buffer.Length == 6) { // header receiver
                    // bytes 2 and 3 contain message length
                    bytes2Read = this.buffer[2] + (this.buffer[3] << 8);
                }
            } while (this.buffer.Length < bytes2Read);

            return this.buffer.ToArray();
        } finally {
            this.buffer.Clear();
        }
    }

The method is situated in the class that derives from SerialPort class.


When you are debugging, you are giving the port driver lots of time to receive a byte. The timeout timer doesn't start running until you step over the ReadByte() call, the driver probably already has received the byte so ReadByte() returns immediately. This doesn't happen when you run at full speed.

Increase the value of the ReadTimeout property. Also consider using the DataReceived event instead.


There seems to be a bug in some virtual COM ports with immediate timeouts immediately after a write. You can partially work around it by inserting a delay after the write (try 10-20 milliseconds), but I haven't found a good solution yet.

Here is discussion on the bug in an ethernet-> RS232 virtual com port


A timeout is normal behavior for the SerialPort. It prevents your application from stalling.

You should be able to modify the ReadTimeout property to increase the time it takes to timeout.

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readtimeout.aspx


sounds like a timing problem. In Debug Mode the program rungs slower than without an attached Debugger. There must be a timing issue

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜