dotnet / dotnet/runtime

Serial port already in use if the USB is reconnected

Open
#122,384 8 comments 0 reactions 0 assignees View on GitHub
area-System.IO.Ports help wanted
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Description

After having a USB modem connected and sending commands through the COM port, I manually unplug it and plug it back in a few seconds later, attempting to open the connection throws the error:
```
The requested resource is in use: COM7' in
System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
at System.IO.Ports.SerialPort.Open()
```

### Reproduction Steps

```
using System.IO.Ports;

partial class Program
{
///
/// Creates and configures a SerialPort instance.
///
private static SerialPort CreatePort(string name)
{
return new SerialPort(name, 115200, Parity.None, 8, StopBits.One);
}

private static void Main()
{
// Change this with your COM port name
string portName = "COM7";

// Open + use port
SerialPort sp = CreatePort(portName);
sp.Open();
sp.WriteLine("AT");

// USER: unplug USB device now
Thread.Sleep(5000);

// Close + dispose before the user plugs it back in
sp.Close();
sp.Dispose();

// USER: plug USB device again now
Thread.Sleep(30000);

// Recreate SerialPort after reconnection
SerialPort sp2 = CreatePort(portName);

// Expected to throw "resource in use" if the issue occurs
try
{
sp2.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
```

### Expected behavior

No error on open

### Actual behavior

IOException

### Regression?

_No response_

### Known Workarounds

_No response_

### Configuration

Windows .Net 10 x64

### Other information

If restart the app works again.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.