非托管对象的内存管理
我有一个关于非托管对象释放的疑问。由于非托管对象不直接受 CLR 控制,因此 CLR 无法直接释放它,为此我们调用 dispose 命令,但如果我们没有在应用程序中对该非托管对象使用 dispose 命令,那么该对象占用的资源将如何释放。
对于前。如果在 C# 代码中我使用连接对象,
try
{
string strConnectionString = "";
strConnectionString = "Server=FTSPROD\\FTS_PROD;Database=tdps_uat;User ID=txnapp;password=txnapp;Min Pool Size=5;Max Pool Size=10000;";
for (int i = 0; i < 10000; i++)
{
SqlConnection cnUpdateTransaction;
cnUpdateTransaction = new SqlConnection(strConnectionString);
cnUpdateTransaction.Open();
cnUpdateTransaction.
//cnUpdateTransaction.Close();
}
}
catch (Exception Ex)
{
}
如下所示,我将打开 10000 个连接对象实例,并将其留给垃圾回收。现在,由于它们是非托管对象,并且我没有调用 close 或 dispose 那么最终将如何释放该对象。操作系统是否会为此执行某些操作以及何时执行。请分享您针对此问题的一些文档链接。
I have one query regarding release of unmanaged objects. As unmanaged objects are not directly under control of CLR so CLR can't release it directly and for that we call dispose command but if we didn't use dispose command in our application for that unmanaged object then how resource occupied by that objects will release .
For Ex. If in C# code I am using connection objects as
try
{
string strConnectionString = "";
strConnectionString = "Server=FTSPROD\\FTS_PROD;Database=tdps_uat;User ID=txnapp;password=txnapp;Min Pool Size=5;Max Pool Size=10000;";
for (int i = 0; i < 10000; i++)
{
SqlConnection cnUpdateTransaction;
cnUpdateTransaction = new SqlConnection(strConnectionString);
cnUpdateTransaction.Open();
cnUpdateTransaction.
//cnUpdateTransaction.Close();
}
}
catch (Exception Ex)
{
}
Here i am opening 10000 instances of connection objects and just leaving it for garbage collection. Now as they are unmanaged objects and i am not calling close or dispose then finally how this objects will be released. Whether operating system will do something for this and when. Please share your with some document link for this issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当实现
IDisposable
并且类具有非托管资源时,您应该实现一个调用Dispose
方法的Finalizer。这样,如果类的用户未能调用 Dispose,非托管资源将(最终)在 GC 运行时被释放。请参阅正确实现 IDisposable 以获得良好的效果例子。如果对象包含对非托管资源的引用并且不包含终结器并且未调用 Dipose,则不会自动回收该内存。基本上,存在内存泄漏。在进程关闭之前,内存不会被回收。请参阅识别并防止托管代码中的内存泄漏获取一些有趣的读物。
When implementing
IDisposable
and the class has unmanaged resources you should implement a Finalizer that calls theDispose
method. That way if the user of the class fails to callDispose
unmanaged resources will (eventually) be released when the GC runs. See Implement IDisposable correctly for a good example.If the object contains references to unmanaged resources and does not contain a finalizer and
Dipose
is not called then that memory will not be reclaimed automatically. Basically, there is a memory leak. The memory won't be reclaimed until the process is shut down. See Identify And Prevent Memory Leaks In Managed Code for some interesting reading.