0

I'm using .dll to in my code so i create object for that, in which .dll open the serial com port but after use it not release the comport. but in my application i want to open comport again but comport occupied by the .dll so it gives error.

please give the solution.

Gaurav
  • 11
  • 1

1 Answers1

0

Your tags got it right - this is the Dispose pattern. The class you are looking for is propably SerialPort:

https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport

You should be using the using Syntax to make sure it is closed. C# 8 even has a new, simpler one for limited scope variables.

The tags confuse me a bit:

  • on the one hand, it can be beneficial to keep such a port open and use the DataReceived() event to react to incomming stuff. In that case the Dispose point depends on the Display technology used/kind of Application.
  • But you also got the ASP.Net tag. And keeping stuff open and ASP.Net do not mix that good. Nevermind the part where COm Ports are not usually controled from a Web Application.

As you said you are using it only for a single write operation, this is the slight modification to the sample code:

   // Create a new SerialPort object with default settings.
   //make a local variable for this
   using (var _serialPort = new SerialPort()){

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();
       //Do stuff with the open port
   }
   //using has it Disposed when you get here. Or otherwise leave the block
Christopher
  • 9,634
  • 2
  • 17
  • 31
  • @Gaurav What is your Display Technology/Environment then? WinForms? WPF? Windows Service? [To be decided]? – Christopher Nov 14 '19 at 05:52
  • i m using window forms. i make application to flash a device. so that i use dll. serial port io.ports.serialport is working well, but when i am using dll file to flash device, it use serial port but not release after flash the device. after that i want to open serial port it gives the error System.UnauthorizedAccessException: 'Access to the port 'COM4' is denied.' so please help me how to release comport from dll file. – Gaurav Nov 14 '19 at 06:00
  • @Gaurav I modified the example code to include a using for a single operation. – Christopher Nov 14 '19 at 06:13