C# – SerialPort in WPF threw I/O Exception

cserial-portwpf

I am work on a very simple program (C# WPF application in VS2010) that display data from SerialPort and display on a TextBox. The program works fine in normal circumstances. But when user open a connection, collect some data, close it, and open it again, and do this for several cycles, the program will eventually throw an exception:

"The I/O operation has been aborted because of either a thread exit or an application request."
[The I/O Exception occurred in the ReadLine()]

Sometime the program would throw me an exception; sometimes the program just hangs.
Below is my code:

/* Click to Open ComPort */
private void PortOpen_Click(object sender, RoutedEventArgs e)
{
    if (!serialPort1.IsOpen)
    {
        serialPort1.PortName = "COM1";
        serialPort1.BaudRate = 9600;
        serialPort1.ReceivedBytesThreshold = 1;
        serialPort1.NewLine = "\r\n";
        serialPort1.Parity = Parity.None;
        serialPort1.StopBits = StopBits.One;
        serialPort1.DataBits = 8;
        serialPort1.Handshake = Handshake.None;

        serialPort1.Open();

        serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Receive);
    }
}

/* Receive data from ComPort */
private void Receive(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    if (serialPort1.IsOpen)
    {
        try
        {
            string1 = serialPort1.ReadLine(); /* This is where I/O Exception occurred */
            Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(DisplayText), string1);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

private void DisplayText(string string1)
{
    textBox1.Text = string1;
}
/* Close ComPort */
private void PortClose_Click(object sender, RoutedEventArgs e)
{
    if (serialPort1.IsOpen)
    {
        serialPort1.Close();
    }            
}

Following summarize my head-banging-against-table attempts in the past 40 hours which result in no progress:

  1. I have tried add Thread.Sleep(3000) before and after Open() and Close(). And I start to get so frustrated that I put Thread.Sleep in between every single line. I though that would allow enough time for some unfinished working in the background. Doesn't solve the problem.
  2. I tried Zach Saw's Post. A lot of comments left on the blog post are very positive. I tried the approach and even copy and paste the exact code to mine. Doesn't solve the problem. A very long post that wasted half of my day.
  3. Kim Hamilton address the issues here. which suggest using BeginInvoke instead of Invoke. Tried and still persist the same problem.
  4. There was a very nice commercial SerialPort library Franson SerialTools which is fairly cheap and works fantastic with no bugs regardless of how many time and how quick I Open() or Close() the serialPort. However, they have discontinue their development and the library they have only works on Form application, not WPF. Some of their argument in their API only accepts Forms.Control. too bad. There are other Commercial product out there but either they are overly priced or do not offer free trail so I wouldn't know whether it works or not before purchase

Does anyone get the .NET SerialPort to work and actually check for bugs (Open() and Close() many times – even when there are no incoming data)?

Best Answer

When you open port you add event handler, when closing i think you should remove it.

Try to do this:

private void PortClose_Click(object sender, RoutedEventArgs e)
{
    if (serialPort1.IsOpen)
    {
        serialPort1.DataReceived -= Receive;
        serialPort1.Close();
    }            
}

Hope this solves problem.

Related Topic