Tuesday, June 19, 2012

SerialPort and C#

The SerialPort class in C# has some interesting behavior when combined with a GUI.  The GUI threads seem to fight with the SerialPort IO.  I found the solution to be to use the BackgroundWorker class.


private void backgroundThread_read(object sender, DoWorkEventArgs e)
{
  BackgroundWorker worker = sender as BackgroundWorker;
  try
  {
     while ((worker.CancellationPending!=true))
     {
                       //serial IO
     }
     //when the shutdown occurs
     if (worker.CancellationPending == true)  
     {
        backgroundThread.CancelAsync();
      }
   }
   catch (Exception exc)
   {
      backgroundThread.CancelAsync();  //cancel the thread due to error
   }
}
I wrapped this with a messaging class that I made.

No comments:

Post a Comment