SerialPort.Close

  • Thread starter Graham McKechnie
  • Start date
G

Graham McKechnie

I mentioned in an earlier thread (Exceptions) that I was having problems
with SerialPort.Close.

I've now modified my Close as follows and I have seemed to overcome that
particular problem

if (this.serialPort.IsOpen)
{
try
{
this.serialPort.ReadTimeout = 0;
this.serialPort.Close();

}
catch (Exception ex)
{
throw new Exception("Failed to close serial port", ex);
}
}

Without the ReadTimeout = 0, it appears to just hang and the GPS lights on
the unit keep on flashing as they do when receiving data - same on 2
different units

Anyone have any ideas why this is necessary or are you not having problems
closing a serial port with the new SerialPort class?

Regards
Graham
 
G

Ginny Caughey [MVP]

Hi Graham,

I spent a little time looking at the SerialPort class with Reflector, and
although I didn't have the patience to trace all the code, I could see that
Close could block until any incoming data event is handled, which is not
what I would have expected. I suspect that the SerialPort class isn't in
wide use yet for reading from a port since most of us have our own code that
we're using instead, so maybe that's why there aren't a lot of other
messages about it.

Thanks for posting your solution.
 
G

Guest

I'm finding the same Locking Application problem if I try to close the serial
port in the Form_closing event. And the serial Port is still receiving data.

with the following code:

if (serialPort1.IsOpen)
serialPort1.Close();

But looking at it in the debugger it doesn't seam to get as far as the close
code before latching the Application;

But if I create dedicated close button on my form, and add the same code to
the click event. Followed by the line:

Application.Exit();

I has no problems at all.
 
G

Graham McKechnie

Wil,
But if I create dedicated close button on my form, and add the same code
to
the click event. Followed by the line:

Application.Exit();

I think you could probably expect that, because I think Application.Exit()
would forceably close all running threads, including the serial thread.

I've since changed my serialPort.Close to not include the ReadTimeOut = 0,
after reading the following
http://blogs.msdn.com/anthonywong/archive/2006/03/03/542625.aspx. Handling
the data asynchronously from serialPort's DataReceived appears to make
serialPort.Close more reliable. However, I'm still having a problem closing
the port after receiving a PowerOnEvent on some ppc's. Anything coming from
a BT serial port always generates an IOException when closing the port after
a powerOnEvent (told it would be fixed in SP1). A CF unit works on some
ppcs, (for PowerOnEvent) but not others.

Graham
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top