当COM转USB转换器从计算机上拔下时,我面临内存泄漏。 内存转储告诉我,我有数百个新的System.Threading.OverlappedData对象。
Type System.Threading.OverlappedData
New objects 246368
New bytes 16753024
Dead bytes 0
Bytes delta 16753024
Type System.IO.Ports.SerialStream+SerialStreamAsyncResult
New objects 246353
New bytes 9854120
Dead bytes 0
Bytes delta 9854120
Type System.Threading._IOCompletionCallback
New objects 246352
New bytes 6897856
Dead bytes 0
Bytes delta 6897856
我的测试应用程序只打开端口,没有事件监听器。使用System;
using System.IO.Ports;
using System.Text;
namespace OpenSerialPortApp
{
class Program
{
static void Main(string[] args)
{
var Sp = new SerialPort
{
StopBits = StopBits.One,
BaudRate = 9600,
DataBits = 8,
Parity = Parity.None,
Encoding = Encoding.UTF8,
PortName = "COM5"
};
Console.WriteLine("Port Created");
Sp.Open();
Console.WriteLine("Port started");
//No I just unplug my COM to USB converter.
Console.ReadKey();
}
}
}
我尝试在拔下插头时关闭并处理串口。但它没有太大的区别。它减少了内存泄漏量,但不能解决我的问题。
private void CloseAndDisposeSerialPort()
{
var localRefToPort = DeviceSerialPort;
DeviceSerialPort = null;
try
{
if (localRefToPort == null) return;
try
{
localRefToPort.Close();
}
catch (Exception cex)
{
//do logging
}
finally
{
try
{
localRefToPort.Dispose();
}
catch (Exception dex)
{
//do logging
}
}
}
catch (Exception ex)
{
//do logging
}
}
内存堆栈无法从UnhandledExceptionHandler获取。
Exception of type 'System.OutOfMemoryException' was thrown.
at System.IO.Ports.SerialStream.EventLoopRunner.WaitForCommEvent()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
我从港口读书时得到的下一个堆栈。 (上面的代码示例没有它)
Exception of type 'System.OutOfMemoryException' was thrown.
at Microsoft.Win32.Win32Native.CreateEvent(SECURITY_ATTRIBUTES lpSecurityAttributes, Boolean isManualReset, Boolean initialState, String name)
at System.Threading.EventWaitHandle..ctor(Boolean initialState, EventResetMode mode, String name)
at System.Threading.ManualResetEvent..ctor(Boolean initialState)
at System.IO.Ports.SerialStream.BeginReadCore(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object stateObject)
at System.IO.Ports.SerialStream.ReadByte(Int32 timeout)
at System.IO.Ports.SerialStream.ReadByte()
at System.IO.Ports.SerialPort.ReadByte()
at TestClass.SerialPortDataReceived(Object sender, SerialDataReceivedEventArgs e)
我认为MSDN上有一篇关于我的问题的文章。但我不确定如何应用建议的解决方案。 我正在与这个问题作斗争将近两周。我试图尽快检测设备断开时刻并关闭/配置端口,但它没有帮助。任何建议都非常感谢。