.Net 2.0 で SerialPort を閉じるときに ObjectDissolvedException が発生する
-
30-10-2019 - |
質問
COM ポート経由で USB ドングルと通信する C# Windows フォーム アプリケーションがあります。通信に .Net 2.0 の SerialPort クラスを使用していますが、シリアル ポート オブジェクトはアプリケーションの存続期間中オープンされています。アプリケーションはデバイスにコマンドを送信し、デバイスから一方的なデータを受信することもできます。
私の問題は、フォームが閉じられたときに発生します。COM ポートを閉じようとすると、(残念ながらランダムに) ObjectDissolvedException が発生します。Windows スタック トレースは次のとおりです。
System.ObjectDisposedException was unhandled
Message=Safe handle has been closed
Source=System
ObjectName=""
StackTrace:
at Microsoft.Win32.UnsafeNativeMethods.SetCommMask(SafeFileHandle hFile, Int32 dwEvtMask)
at System.IO.Ports.SerialStream.Dispose(Boolean disposing)
at System.IO.Ports.SerialStream.Finalize()
InnerException:
同様の問題を抱えている人々の投稿を見つけて、[ここ][1]の回避策を試してみました。
[1]: http://zachsaw.blogspot.com/2010/07/net-serialport-woes.html ただし、これは IOException に関するものであり、問題は解決しませんでした。
私のClose()コードは次のとおりです。
public void Close()
{
try
{
Console.WriteLine("******ComPort.Close - baseStream.Close*******");
baseStream.Close();
}
catch (Exception ex)
{
Console.WriteLine("******ComPort.Close baseStream.Close raised exception: " + ex + "*******");
}
try
{
_onDataReceived = null;
Console.WriteLine("******ComPort.Close - _serialPort.Close*******");
_serialPort.Close();
}
catch (Exception ex)
{
Console.WriteLine("******ComPort.Close - _serialPort.Close raised exception: " + ex + "*******");
}
}
私のログ記録では、実行が SerialPort の BaseStream を閉じる試みを超えていないことがわかりました (これは最初の行にあります) try
ブロック)のため、この行を削除してみましたが、依然として例外が定期的にスローされます - 2番目のログ try
ブロックが表示されてから例外が発生しました。どちらの catch ブロックも例外をキャッチしません。
何か案は?
更新 - 完全なクラスを追加:
namespace My.Utilities
{
public interface ISerialPortObserver
{
void SerialPortWriteException();
}
internal class ComPort : ISerialPort
{
private readonly ISerialPortObserver _observer;
readonly SerialPort _serialPort;
private DataReceivedDelegate _onDataReceived;
public event DataReceivedDelegate OnDataReceived
{
add { lock (_dataReceivedLocker) { _onDataReceived += value; } }
remove { lock (_dataReceivedLocker) { _onDataReceived -= value; } }
}
private readonly object _dataReceivedLocker = new object();
private readonly object _locker = new object();
internal ComPort()
{
_serialPort = new SerialPort { ReadTimeout = 10, WriteTimeout = 100, DtrEnable = true };
_serialPort.DataReceived += DataReceived;
}
internal ComPort(ISerialPortObserver observer) : this()
{
_observer = observer;
}
private void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
DataReceivedDelegate temp = null;
lock (_locker)
{
lock (_dataReceivedLocker)
{
temp = _onDataReceived;
}
string dataReceived = string.Empty;
var sp = (SerialPort) sender;
try
{
dataReceived = sp.ReadExisting();
}
catch (Exception ex)
{
Logger.Log(TraceLevel.Error, "ComPort.DataReceived raised exception: " + ex);
}
if (null != temp && string.Empty != dataReceived)
{
try
{
temp(dataReceived, TickProvider.GetTickCount());
}
catch (Exception ex)
{
Logger.Log(TraceLevel.Error, "ComPort.DataReceived raised exception calling handler: " + ex);
}
}
}
}
public string Port
{
set
{
try
{
_serialPort.PortName = value;
}
catch (Exception ex)
{
Logger.Log(TraceLevel.Error, "ComPort.Port raised exception: " + ex);
}
}
}
private System.IO.Stream comPortStream = null;
public bool Open()
{
SetupSerialPortWithWorkaround();
try
{
_serialPort.Open();
comPortStream = _serialPort.BaseStream;
return true;
}
catch (Exception ex)
{
Logger.Log(TraceLevel.Warning, "ComPort.Open raised exception: " + ex);
return false;
}
}
public bool IsOpen
{
get
{
SetupSerialPortWithWorkaround();
try
{
return _serialPort.IsOpen;
}
catch(Exception ex)
{
Logger.Log(TraceLevel.Error, "ComPort.IsOpen raised exception: " + ex);
}
return false;
}
}
internal virtual void SetupSerialPortWithWorkaround()
{
try
{
//http://zachsaw.blogspot.com/2010/07/net-serialport-woes.html
// This class is meant to fix the problem in .Net that is causing the ObjectDisposedException.
SerialPortFixer.Execute(_serialPort.PortName);
}
catch (Exception e)
{
Logger.Log(TraceLevel.Info, "Work around for .Net SerialPort object disposed exception failed with : " + e + " Will still attempt open port as normal");
}
}
public void Close()
{
try
{
comPortStream.Close();
}
catch (Exception ex)
{
Logger.Log(TraceLevel.Error, "ComPortStream.Close raised exception: " + ex);
}
try
{
_onDataReceived = null;
_serialPort.Close();
}
catch (Exception ex)
{
Logger.Log(TraceLevel.Error, "ComPort.Close raised exception: " + ex);
}
}
public void WriteData(string aData, DataReceivedDelegate handler)
{
try
{
OnDataReceived += handler;
_serialPort.Write(aData + "\r\n");
}
catch (Exception ex)
{
Logger.Log(TraceLevel.Error, "ComPort.WriteData raised exception: " + ex);
if (null != _observer)
{
_observer.SerialPortWriteException();
}
}
}
}
}
正しい解決策はありません
所属していません StackOverflow