Here is the code which reads data from a serial port. To keep the things simple, let's do it on a button click;
private System.IO.Ports.SerialPort serialPort;
private void button1_Click(object sender, EventArgs e)
{
if (serialPort == null)
serialPort = new SerialPort("COM7", 4800, Parity.None, 8, StopBits.One);
//COM7 is hard coded just for the sake of example
if (!serialPort.IsOpen)
serialPort.Open();
textBox1.AppendText(serialPort.ReadExisting());
}
The code runs perfectly fine unless my laptop goes to sleep. When the system wakes-up from sleep, the serialPort
object is not null
but serialPort.IsOpen
returns false
and I get the error, "The requested resource is in use." while calling serialPort.Open()
. There is nothing in the inner exception.
I have tried many things with serialPort
object like closing, disposing or explicitly assigning it to null and reinitialization but it's of no use, same error on same line every time.
if (!serialPort.IsOpen)
{
try
{
serialPort.Open();
}
catch
{
serialPort.Close();
serialPort.Dispose();
serialPort = null;
serialPort = new SerialPort("COM7", 4800, Parity.None, 8, StopBits.One);
serialPort.Open();
}
}
I also have tried serialPort.DataReceived
event but the event is not fired once the system woke-up from sleep.
The only workaround is to stop the application and run it again. I will really appreciate if anyone give me a clue to sort it out in a decent manner.
As I suggested in comment the workaround could be made by using SystemEvents.PowerModeChanged
event to detect when system is about to suspend. When that state is detected you need to close serial port and reopen it when operating system is about to resume from a suspended state.
hamad confirmed that this workaround works.
Here is the code.
SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
if (e.Mode != PowerModes.Resume)
serialPort.Close();
}
Also note from documentation of event:
Caution
Because this is a static event, you must detach your event handlers when your application is disposed, or memory leaks will result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With