1

I have a piece of code like this:

public class SerialPortListener
{

    #region Properties

    public SerialPort _Port { get; set; }
    public event EventHandler<SerialDataEventArgs> DataReceived;

    #endregion


    public void Start()
    {
        Close();

        //todo: get attached COM names...
        List<string> names = SerialPort.GetPortNames().ToList();

        // todo: for testing, let's pick first...
        string name = names.FirstOrDefault();

        if (string.IsNullOrEmpty(name))
            return; // todo: throw error that no devices are attached...

        _Port = new SerialPort(name);
        _Port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        _Port.Open();
    }

    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort port = (SerialPort)sender;
        string data = port.ReadExisting();
        if (DataReceived != null)
            DataReceived(this, new SerialDataEventArgs(data));
    }

    public void Close()
    {
        if (_Port != null && _Port.IsOpen)
            _Port.Close();
    }

}

public class SerialDataEventArgs : EventArgs
{
    public SerialDataEventArgs(string data)
    {
        Data = data;
    }

    /// <summary>
    /// Byte array containing data from serial port
    /// </summary>
    public string Data;
}

where com port name is "COM1", and I have connected a handheld barcode scanner. I noticed that it works only when I put a breakpoint on _Port.Open() and then step over it after which I press continue in the debugger. Then scanning works and DataReceivedHandler is called.

Otherwise it doesn't work and scanner also doesn't get a good read beep. I Tested scanner in the application I got from here ,where it works fine every time.

My question is why doesn't it work every time like in example app and what can be done differently to make it work.

6
  • what is the baudrate of the scanner, and why don't you specify it? Commented Jan 8, 2018 at 15:33
  • Do you gracefully close the port an application exit? If so do you quit the app while debugging or do you hit "stop"? My first thought would be the port is not correctly freed. And you should use some try/catches to figure out what's the matter when things go south. Another thing: You take the first portname in the list. Where do you make sure it is actually "COM1" ? Commented Jan 8, 2018 at 15:33
  • @MongZhu the baudrate is left as default 9600 Commented Jan 8, 2018 at 16:51
  • @Fildor I will try to use the "Close" and then let you know, thanks :) Commented Jan 8, 2018 at 16:51
  • Make sure scanner is connected before executing the start function and if you want to recognize when any device is getting connected and auto start then that's the different question. I can provide code if you want to recognize when any devices are connected to the serial port if you need it. Commented Jan 8, 2018 at 18:04

1 Answer 1

1

When using COM ports, it is important to close them after use. Otherwise they will remain unavailable for opening again until they are closed.

Therefore, when debugging, it is important to not simply hit "stop debugging" but have some cleanup code running in all circumstances that will gracefully close the port.

I'd also recommend adding an unhandled exception handler in the App that makes sure the port will be closed before exiting the Application in case of an unexpected error.

Also, the documentation of the "Open" method states under "Remarks":

The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.