Reputation: 1275
I'm working in Visual Studio C#, and I opened up a serial port, but I didn't properly close it. Now I cannot run my program to try to close it. I know it was me that was using it, but somehow I've lost control of it..? Is there a way to close it otherwise?
I've tried exiting out of visual studio and it still says that my access is denied. I've unplugged and replugged in the actual object I'm using. My next step is to restart the computer, but I don't want to have to do that everytime I mess up (which is frequently!)
On a side-note, I'm working in a lab and do not have administrative access on this computer. Another note is that the error's text is "Access to the port 'COM1' is denied."
In response to those asking for code,.. comPort.Open(); What else are you looking for?
private void updateAccuSwayData() {
Console.WriteLine("Update thread started...");
comPort.Open();
comPort.WriteLine("Q");
Thread.Sleep(5);
while (!cancelRequested) {
//do stuff...
}
Console.WriteLine("Update thread halted.");
comPort.WriteLine("R");
comPort.Close();
}
In a nutshell, I ended my debugging session while it was in middle of something it seems. That's about all I know.
Upvotes: 2
Views: 2356
Reputation: 64068
You'll likely need to reboot to clear this up, although one approach would be to use Process Explorer and search for a handle to \Device\Serial0
. You can then see if closing this handle works, it may not however.
To work to keep this from happening in the future, you need to put the comPort.Close()
call in a finally
-block:
try
{
comPort.Open();
// ...
}
finally
{
// Almost always ensures the COM port will be cleaned up,
// however, the MSDN remarks state that the port may not
// be closed immediately.
comPort.Close();
}
Upvotes: 5