Frage

I have a serial port and I would like to keep it hanging open to receive messages. Is this the correct way to do so? I would like to accomplish this without the while loop, but I think if it is removed it will complete the void() and the connection. Or is that incorrect and so long as I don't close the connection it will continue to receive data (see code block 2)?

      public void Scanner(object sp)
      {

        this.sp = (SerialPort)sp;

        this.sp.Open();
        this.sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
        Console.WriteLine("port {0} open waiting message", this.sp.PortName);
        while (!_terminate)
        {
            Thread.Sleep(100);
        }
        Console.WriteLine("termination code received closing port {0}.", this.sp.PortName);
        this.sp.Close();
      } 

or like this?

      public void Scanner(object sp)
      {

        this.sp = (SerialPort)sp;

        this.sp.Open();
        this.sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
      }

The other thing is I feel I should move that event handler outside the void. The void is being called by a ParameterizedThreadStart so it's signature must be void name(object o){}. I think I should be moving it to the constructor correct?

constructor as is now

   public SerialComms(){}

What I think it should be

   public SerialComms()
   {  
     this.sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
   }
War es hilfreich?

Lösung

Basically I think block 2 is better because you get an asynchronous notification if there is data available. As long as you dont call the "close" method for the comport, it will receive the data.

Furthermore I suggest (regarding the event topic) to make two seperated methods like:

public void OpenPort()
{
     this.sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
     this.sp.Open();
}

public void ClosePort()
{
     this.sp.Close();
     this.sp.DataReceived -= new SerialDataReceivedEventHandler(sp_DataReceived);
}

The second method is very important to deregister the event. For example if you close your application. Otherwise your application will hang. Always deregister events if you registered to them, because also the event handler is stopping the Garbage Collection from cleaning up your objects.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top