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();
- :)