Skip to content

Commit

Permalink
Created a SerialDevice.SafeClosePort method that catches several exce…
Browse files Browse the repository at this point in the history
…ptions that can sometimes occur when calling SerialPort.Close
  • Loading branch information
JamesMessinger committed Dec 15, 2009
1 parent 90562ed commit 8a709eb
Showing 1 changed file with 25 additions and 14 deletions.
39 changes: 25 additions & 14 deletions Devices/SerialDevice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,7 @@ protected override Stream OpenStream(FileAccess access, FileShare sharing)
protected override void OnDisconnecting()
{
// Close the port if it's open
if (_Port.IsOpen)
_Port.Close();
SafeClosePort();

// And continue
base.OnDisconnecting();
Expand Down Expand Up @@ -596,18 +595,8 @@ protected override bool DetectProtocol()
#if !PocketPC
public override void CancelDetection()
{
if (IsDetectionInProgress && _Port != null && _Port.IsOpen)
{
try
{
// There are several errors that can occur within the SerialPort.Close method,
// despite the above checks. Thus, all the empty catch blocks below.
_Port.Close();
}
catch (ArgumentNullException) {}
catch (NullReferenceException) {}
catch (ObjectDisposedException) {}
}
if (IsDetectionInProgress)
SafeClosePort();

// Continue to abort the thread
base.CancelDetection();
Expand Down Expand Up @@ -1305,6 +1294,28 @@ private static void LoadWindowsDevices(IList<SerialDevice> devices)
#endif
}

#if !PocketPC
/// <summary>
/// Closes the serial port, and ignores several exceptions that are outside of our control.
/// </summary>
private void SafeClosePort()
{
if (_Port != null && _Port.IsOpen)
{
try
{
// There are several errors that can occur within the SerialPort.Close method,
// despite the above checks. Thus, all the empty catch blocks below.
_Port.Close();
}
catch (IOException) { }
catch (ArgumentNullException) { }
catch (NullReferenceException) { }
catch (ObjectDisposedException) { }
}
}
#endif

#endregion

#region IEquatable<SerialDevice> Members
Expand Down

0 comments on commit 8a709eb

Please sign in to comment.