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 6232677
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T10:09:27+00:00 2026-05-24T10:09:27+00:00

I got the code below from a website,and this way of serial port reading

  • 0

I got the code below from a website,and this way of serial port reading is my only option because DataReceived event often doesn’t work.but this code has a problem,if I close the application while transfering the application hangs forever,but I can’t see why?neither freezing nor aborting the thread work.actually aborting the thread causes the program to crash.

public class CommPort
{
    SerialPort _serialPort;
    Thread _readThread;
    bool _keepReading;

    //begin Singleton pattern
    static readonly CommPort instance = new CommPort();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static CommPort()
    {
    }

    CommPort()
    {
        _serialPort = new SerialPort();
        _readThread = null;
        _keepReading = false;
    }

    public static CommPort Instance
    {
        get
        {
            return instance;
        }
    }
    //end Singleton pattern

    //begin Observer pattern
    public delegate void EventHandler(string param);
    public EventHandler StatusChanged;
    public EventHandler DataReceived;

    private void StartReading()
    {
        if (!_keepReading)
        {
            _keepReading = true;
            _readThread = new Thread(new ThreadStart(ReadPort));
            _readThread.Start();
        }
    }
    private void StopReading()
    {
        if (_keepReading)
        {
            _keepReading = false;
            _serialPort.Close();
            //_readThread.Join();   //block until exits
            _readThread.Abort();
            //_readThread = null;
        }
    }
    private void ReadPort()
    {
        while (_keepReading)
        {
            if (_serialPort.IsOpen)
            {
                byte[] readBuffer = new byte[_serialPort.ReadBufferSize + 1];
                try
                {
                    // If there are bytes available on the serial port,
                    // Read returns up to "count" bytes, but will not block (wait)
                    // for the remaining bytes. If there are no bytes available
                    // on the serial port, Read will block until at least one byte
                    // is available on the port, up until the ReadTimeout milliseconds
                    // have elapsed, at which time a TimeoutException will be thrown.
                    int count = _serialPort.Read(readBuffer, 0, _serialPort.ReadBufferSize);
                    String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer, 0, count);
                    DataReceived(SerialIn);
                }
                catch (TimeoutException)
                {
                }
            }
            else
            {
                TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50);
                Thread.Sleep(waitTime);
            }
        }
    }


    /// <summary> Open the serial port with current settings. </summary>
    public void Open()
    {
        Close();

        try
        {
            _serialPort.PortName = Properties.Settings.Default.COMPort;
            _serialPort.BaudRate = Properties.Settings.Default.BPS;
            _serialPort.Parity = Properties.Settings.Default.Parity;
            _serialPort.DataBits = Properties.Settings.Default.DataBit;
            _serialPort.StopBits = Properties.Settings.Default.StopBit;
            _serialPort.Handshake = Properties.Settings.Default.HandShake;

            // Set the read/write timeouts
            _serialPort.ReadTimeout = 50;
            _serialPort.WriteTimeout = 50;

            _serialPort.Open();
            StartReading();
        }
        catch (IOException)
        {
            StatusChanged(String.Format("{0} does not exist", Properties.Settings.Default.COMPort));
        }
        catch (UnauthorizedAccessException)
        {
            StatusChanged(String.Format("{0} already in use", Properties.Settings.Default.COMPort));
        }
        catch (Exception ex)
        {
            StatusChanged(String.Format("{0}", ex.ToString()));
        }

        // Update the status
        if (_serialPort.IsOpen)
        {
            string p = _serialPort.Parity.ToString().Substring(0, 1); //First char
            string h = _serialPort.Handshake.ToString();
            if (_serialPort.Handshake == Handshake.None)
                h = "no handshake"; // more descriptive than "None"

            StatusChanged(String.Format("{0}: {1} bps, {2}{3}{4}, {5}",
            _serialPort.PortName, _serialPort.BaudRate,
            _serialPort.DataBits, p, (int)_serialPort.StopBits, h));
        }
        else
        {
            StatusChanged(String.Format("{0} already in use", Properties.Settings.Default.COMPort));
        }
    }

    /// <summary> Close the serial port. </summary>
    public void Close()
    {
        StopReading();
        StatusChanged("connection closed");
    }
    public bool IsOpen
    {
        get
        {
            return _serialPort.IsOpen;
        }
    }
}
  • 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-24T10:09:27+00:00Added an answer on May 24, 2026 at 10:09 am

    When you close the Port in StopReading() it will cause an Exception in _serialPort.Read(…).

    Not sure which one exactly but it’s not a TimeOut. Your current code lets that escape and that’s when your thread and your App are killed.

    So add a catch(Exceptiopn ex) around the while loop in ReadPort().

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

Sidebar

Related Questions

I got this code below from a tutorial I'm using to learn PHP. I
I got code snippet from this site, which I used as shown below $data
I got this from php.net website. This is related to the problem I am
I have the code below which I got from the php: mktime manual just
I got the code below from a tutorial that teaches how to make wordpress
I know there is alot on this topic already. I got the code below
i've got the below code, and it operates just fine, only it takes a
In my android app I've got the below code creating my database. This works
So far i have got the code below which works lovely when trying an
I first got an error usign the code below, explaining that DataGridLinkButton' must be

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.