Serial Port Release

I am writing an application in C # that uses a class SerialPortto communicate with multiple devices. Now the big problem that I have encountered all the time is to free resources correctly there, since you immediately get an exception when trying to use an already used serial port.

Since GC usually has to take care of most of the work, because of the ideas I don’t understand what else to try ...

Basically I tried two things that (by my logic) should do the job. I use a session connection, so I call the method OpenPort, and ClosePortbefore and after each message - so the port should be closed. In addition, I tried to set my object containing the port to null, but I still get it UnauthorizedAccessExceptionsall the time, although I am 100% sure that the method was called SerialPort.Close().

Do you guys know any better ways to free ports so that I stop getting this exception?

EDIT: Thanks for the answers, but Dispose () stuff doesn't work - I tried to do this before - maybe I'm doing something wrong, although here is an example of what my code looks like:

Actually, it was similar to what Øyvind suggested, although I just added IDisposable- but it doesn't work:

So this will be my shell class:

class clsRS232 : IDisposable
{
  public void clsRS232()
  {
    Serialport port = new Serialport("COM1",9600,Parity.none,8,Stopbits.one);
  }
  public void openPort()
  {
     port.Open();
  }
  public void sendfunc(string str)
  {
    port.Write(str);
  }
  public string readfunc()
  {
    port.ReadTo("\n");
  }

  public void Dispose()
  {
     port.Dispose();
  }

}

, rs232, :

   clsRS232 test = new clsRS232;
   test.openport();
   test.sendfunc("test");
   test.Dispose();

- UnauthorizedAccessExceptions - ( Dispose() SerialPort SerialPort.Close()) - , , t - , close();

- :)

+5
3

SerialPort IDisposable, :

using( SerialPort port = new SerialPort( ... ) ){
  //do what you need with the serial port here
}

, using , using, , using , try/finally, / SerialPort finally.

OP SerialPort , .

, . . IDisposable SerialPort Dispose.

, / .

, , , , , , , , - COM- .

2

:

clsRS232 test = new clsRS232;
test.openport();
test.sendfunc("test");
test.Dispose();

, sendfunc - , . IDisposable , , :

using( clsRS232 test = new clsRS232 ){
 test.openport();
 test.sendfunc("test");
}

, Dispose COM-, - using.

+6

, , , , . com-? ​​SerialPortClass. -, . SerialPort Dispose , :

  private SerialPort KickerPort { get; set; }
    .
    .
    .
private bool OpenPort()
        {
            ///questions/660480/why-is-access-to-com-port-denied
            //due to a bug in the SerialPort code, the serial port needs time to dispose if we used this recently and then closed
            //therefore the "open" could fail, so put in a loop trying for a few times
            int sleepCount = 0;
            while (!TryOpenPort())
            {
                System.Threading.Thread.Sleep(100);
                sleepCount += 1;
                System.Diagnostics.Debug.Print(sleepCount.ToString());
                if (sleepCount > 50) //5 seconds should be heaps !!!
                {
                    throw new Exception(String.Format("Failed to open kicker USB com port {0}", KickerPort.PortName));
                }
            }
            return true;
        }
     private bool TryOpenPort()
                {
                    if (!KickerPort.IsOpen)
                    {
                        try
                        {
                            KickerPort.Open();
                            return true;
                        }
                        catch (UnauthorizedAccessException)
                        {
                            return false;
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }

                    }
                    return true;
                }

:

 try
            {
                if (OpenPort())
                {
                    //do your thing here !
                }
                return false;
            }
            catch (Exception ex)
            {  
                throw ex;
            }

( , USB-), , , 20 ,

+2

The implementation proposed by Øyvind Bråthen uses the IDisposable template in .NET. At the end of the block in use, the Dispose function of the SerialPort instance is called, which will release the associated unmanaged resources (i.e., the serial port)

Calling .Dispose () port when you want to release it.

0
source

All Articles