tags:

views:

188

answers:

3

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.

A: 

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

Daniel A. White
A: 

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

Christoferw
+2  A: 

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.

Hans Passant
+1 Highly recommend using DataReceived event
SwDevMan81