title: Freeing up Serial Port properly
body: <p>I'm writing an app in c# that utilizes the <code>SerialPort</code> class to communicate with a few devices. Now the big problem I've been encountering all the time is how to properly free up resources there, since you immediately get an exception when trying to use a serial port that is already being used.</p>
  
  <p>Since normally the GC should take care of most of the work I'm kinda out of ideas what else to try...</p>
  
  <p>Mainly I tried 2 things which (in my logic) should do the work. I use session based communication, so I call an <code>OpenPort</code> and a <code>ClosePort</code> method before and after every communication - so the port should be closed. Also I've tried setting my object containing the port to null afterwards - but still I get <code>UnauthorizedAccessExceptions</code> all the time - although I am 100 percent sure that the <code>SerialPort.Close()</code> method has been called.</p>
  
  <p>Do you guys know any better ways of freeing up the ports so I stop getting that exception?</p>
  
  <p>EDIT:
  Thanks for the answers but the Dispose() stuff isn't working - I had tried that before - maybe I'm doing something wrong though so here's an example what my code looks like:</p>
  
  <p>It's actually quite like Øyvind suggested, though I just added the <code>IDisposable</code> - but doesn't work either:</p>
  
  <p>So this would be my wrapper class:</p>
  
  <pre><code>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();
    }
  
  }
  </code></pre>
  
  <p>Now whenever I need rs232 communication I call a new instance like this:</p>
  
  <pre><code>   clsRS232 test = new clsRS232;
     test.openport();
     test.sendfunc("test");
     test.Dispose();
  </code></pre>
  
  <p>But that doesn't change anything - I still get lots of UnauthorizedAccessExceptions - and if the other guy was right (that Dispose() of SerialPort-class only contains SerialPort.Close() ) - well then I guess I haven't really changed anything from my earlier approach, where I had a function call close();</p>
  
  <p>thanks for your answers - still hoping to find the solution :)</p>