Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 333767
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T09:59:31+00:00 2026-05-12T09:59:31+00:00

Good afternoon everybody! I have this threaded SerialPort wrapper that reads in a line

  • 0

Good afternoon everybody!

I have this threaded SerialPort wrapper that reads in a line from the serial port. Here is my thread’s code.

protected void ReadData()
{
     SerialPort serialPort = null;
     try
     {
         serialPort = SetupSerialPort(_serialPortSettings);
         serialPort.Open();

         string data;
         while (serialPort.IsOpen)
         {
             try
             {

                 data = serialPort.ReadLine();
                 if (data.Length > 0)
                     ReceivedData(serialPort, new ReceivedDataEventArgs(data));

             }
             catch (TimeoutException)
             {
                 //  No action
             }
         }
     }
     catch (ThreadAbortException)
     {
         if (serialPort != null)
             serialPort.Close();
     }
}

when I call myThread.Abort(); I get an exception (with no line or reference to code) “Safe handle has been closed”. Can anyone spot what I am doing wrong? Thanks.

By the way, I have a Start() and a Stop() that creates the thread and aborts the thread, respectfully.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T09:59:31+00:00Added an answer on May 12, 2026 at 9:59 am

    I would suspect that it is because you are using Thread.Abort to end the thread – which is generally frowned upon. The thread behavior when you abort it is not predictable. Because of that, since the serial port is a wrapper over native code, there are native resources – represented by a SafeHandle in .NET – which get disposed of unexpectedly and so you get the Exception.

    You can think about what happens with your thread like this:

    • you start your thread
    • you open the serial port (which allocates native resources and uses SafeHandle(s) to hold on to those resources)
    • you start reading from the serial port
    • then at some point (unexpected to your thread) you call Thread.Abort on it
    • most likely the code in your thread is at that point trying to access the serial port (to read data)
    • the thread gets killed and the serial port handle is destroyed implicitly
    • you get an exception thrown from the code inside the ReadLine() function of the serial port because the handle it had is no longer valid

    You really should use a different method for aborting the thread so that you get a proper chance to close and dispose of the serial port.

    A proper way to close your thread could be implemented using a ManualResetEvent like this:

    protected ManualResetEvent threadStop = new ManualResetEvent(false);
    
    protected void ReadData()
    {
         SerialPort serialPort = null;
         try
         {
             serialPort = SetupSerialPort(_serialPortSettings);
             serialPort.Open();
    
             string data;
             while (serialPort.IsOpen)
             {
                 try
                 {
    
                     data = serialPort.ReadLine();
                     if (data.Length > 0)
                         ReceivedData(serialPort, new ReceivedDataEventArgs(data));
    
                 }
                 catch (TimeoutException)
                 {
                     //  No action
                 }
    
                 // WaitOne(0) tests whether the event was set and returns TRUE
                 //   if it was set and FALSE otherwise.
                 // The 0 tells the manual reset event to only check if it was set
                 //   and return immediately, otherwise if the number is greater than
                 //   0 it will wait for that many milliseconds for the event to be set
                 //   and only then return - effectively blocking your thread for that
                 //   period of time
                 if (threadStop.WaitOne(0))
                     break;
             }
         }
         catch (Exception exc)
         {
             // you can do something here in case of an exception
             // but a ThreadAbortedException should't be thrown any more if you
             // stop using Thread.Abort and rely on the ManualResetEvent instead
         }
         finally
         {
             if (serialPort != null)
                 serialPort.Close();
         }
    }
    
    protected void Stop()
    {
        // Set the manual reset event to a "signaled" state --> will cause the
        //   WaitOne function to return TRUE
        threadStop.Set();
    } 
    

    Of course, when using the events method to stop the thread you have to be careful to include an event state check in all your long running loops or tasks. If you don’t your thread may appear not to respond to your setting the event – until it gets out of the long-running loop, or task and gets a chance to “see” that the event has been set.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Good afternoon, I have three entities (that concern this question) Company (ID, etc..) CompanyAddress
Good Afternoon all , I have downloaded data from a web service and im
Good Afternoon, I have a html aspx page that has many many div elements.
Good afternoon people's I have built a jquery plugin that I use on my
Good Afternoon All, I have written an SSIS 2005 package that contains a conditional
Good afternoon, everybody. I have a doubt. I have a WHILE, and accurate list
Good afternoon everybody, first of all I hope this is the correct place to
Good afternoon all Here is my scenario: I have user controls within a master
Good afternoon. I have been making a small openGL based app for android that
Good afternoon, Wow what a title. Basically here is the thing. If have a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.