faxad
faxad

Reputation: 423

release COM port after killing process

I have a C# application that uses D-Link GSM Modem to send/receive SMS messages.

Now for some reason the D-Link USB gets disconnected and reconnected automatically after some time (random). When it re-connects it opens up the D-Link Connection Manager which reserves the COM4.

Now when my application run and tries to send SMS it fails, because it doesn't find any available (already in use my D-Link Manager).

when i tried as at application load if the D-Link Process is there I'm killing it using process.kill(). That kills the application but still the COM4 remains inaccessible.

Is there a way to kill the process and release the COM port also programmatically ?

Upvotes: 1

Views: 1773

Answers (3)

Lucas Blinda
Lucas Blinda

Reputation: 1

one should blame poorly designed operating system for not being capable to clean the resources of the process after killing it

Upvotes: 0

John Saunders
John Saunders

Reputation: 161773

The SerialPort class implements IDisposable for exactly this reason: to clean up unmanaged resources (like the port itself) when the port variable goes out of scope.

using (var serialPort = new SerialPort())
{
    // Set the read/write timeouts
    serialPort.ReadTimeout = 500;
    serialPort.WriteTimeout = 500;

    serialPort.Open();

    // do something
}

It won't always get cleaned up when you kill the process, but this way, you're giving it a fighting chance.

Upvotes: 0

Tom Blodget
Tom Blodget

Reputation: 20772

Killing a process doesn't give it a chance to clean up. It is easy for COM ports to get hung up if clients terminate abnormally.

Try Process.CloseMainWindow. Hopefully, the process will respond by shutting down normally and closing the COM port. You would have to give it some time to shut down, though, for which you could use Process.WaitForExit.

Upvotes: 1

Related Questions