Opened SerialPort crashes C# application

Posted by Stefan Teitge on Stack Overflow See other posts from Stack Overflow or by Stefan Teitge
Published on 2009-04-28T11:31:00Z Indexed on 2010/03/20 19:11 UTC
Read the original article Hit count: 513

The computer is connected to measuring device via a physical COM1. I have simple form where I open a serial port, tell the device that I'm alive and occasionally the device sends data. (every some minutes)

Thread _readThread = new Thread(Read);
SerialPort _serialPort = new SerialPort("COM1", 9600);
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
_serialPort.DtrEnable = true;
_serialPort.Open();
_readThread.Start();
_serialPort.Write("#listening");

The read function (which works):

public void Read()
{
    string message = _serialPort.ReadLine();
}

After approximately one minute the application crashes (even while debugging). It reports an ObjectDisposedException (for the underlying stream?). The message tells that the SafeHandle was closed. Stack strace is below:

at Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(SafeFileHandle hFile, NativeOverlapped lpOverlapped, Int32& lpNumberOfBytesTransferred, Boolean bWait) at System.IO.Ports.SerialStream.EventLoopRunner.WaitForCommEvent() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()*

Any ideas? The problem is reported widely but usually involve the device beeing physically detached from the PC.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET