主题:求助:非托管代码的资源释放问题
我用C#写了一个类,调用一个C++类(名称为:GetSecurityTypeFromCodeMarket.dll),
当我在程序中大量的使用这个C#的类之后,发现内存消耗特别快,直到程序耗紧系统内存而强迫推出,我估计是这个C#的类写的有问题,没有把非托管的资源释放掉,请高手帮我看看,谢谢了!
C#类的代码
public class GetSecuritiesInfoClass: IDisposable
{
private static IntPtr instancePtr;
bool disposed = false;
public GetSecuritiesInfoClass()
{
instancePtr = CreateInstance();
}
//C++DLL中导出一个类,EntryPoint在.LIB文件中可以找到,一旦类修改或者方法签名改变,需要改变此EntryPoint
[ DllImport( "GetSecurityTypeFromCodeMarket.dll")]
private static extern IntPtr CreateInstance();
[ DllImport( "GetSecurityTypeFromCodeMarket.dll" )]
private static extern void DeleteInstance( IntPtr instance ); //本函数直接调用C++ dll中析构函数中函数体代码
public string GetSecurityTypeFromCodeMarket(string marketCode)
{
//code...
}
//释放非托管资源
~ GetSecuritiesInfoClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!disposed)
{
if(disposing)
{
// Release managed resources.
this.Dispose();
}
// Free the unmanaged resource ...
instancePtr = IntPtr.Zero;
DeleteInstance( instancePtr );
disposed = true;
}
}
}
当我在程序中大量的使用这个C#的类之后,发现内存消耗特别快,直到程序耗紧系统内存而强迫推出,我估计是这个C#的类写的有问题,没有把非托管的资源释放掉,请高手帮我看看,谢谢了!
C#类的代码
public class GetSecuritiesInfoClass: IDisposable
{
private static IntPtr instancePtr;
bool disposed = false;
public GetSecuritiesInfoClass()
{
instancePtr = CreateInstance();
}
//C++DLL中导出一个类,EntryPoint在.LIB文件中可以找到,一旦类修改或者方法签名改变,需要改变此EntryPoint
[ DllImport( "GetSecurityTypeFromCodeMarket.dll")]
private static extern IntPtr CreateInstance();
[ DllImport( "GetSecurityTypeFromCodeMarket.dll" )]
private static extern void DeleteInstance( IntPtr instance ); //本函数直接调用C++ dll中析构函数中函数体代码
public string GetSecurityTypeFromCodeMarket(string marketCode)
{
//code...
}
//释放非托管资源
~ GetSecuritiesInfoClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!disposed)
{
if(disposing)
{
// Release managed resources.
this.Dispose();
}
// Free the unmanaged resource ...
instancePtr = IntPtr.Zero;
DeleteInstance( instancePtr );
disposed = true;
}
}
}