c# – 垃圾收集和使用 – 为什么在使用{}`块后没有释放内存?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 垃圾收集和使用 – 为什么在使用{}`块后没有释放内存?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2188字,纯文字阅读大概需要4分钟。
内容图文
![c# – 垃圾收集和使用 – 为什么在使用{}`块后没有释放内存?](/upload/InfoBanner/zyjiaocheng/962/111bb567cd364668ae251730ee9d1b80.jpg)
我最近一直在重构一些旧的数据库访问代码.我有一个包含数百种方法的库,看起来像这样
public int getFoo(int id)
{
using(SqlConnection connection = ConnectionManager.GetConnection())
{
string sql = "SELECT TOP(1) foo FROM bar WHERE id=@id";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@id", id);
return (int)command.ExecuteScalar();
}
}
我认为将SqlCommands包装到using {}块(就像SqlConnection已经存在)是一个明智的事情,这样资源就会尽快被处理掉.出于好奇心,我决定制作以下小型控制台应用程序,以查看将释放多少内存:
using (SqlConnection conn = ConnectionManager.GetConnection())
{
WeakReference reference;
string sql = "SELECT COUNT(foo) FROM bar";
Console.WriteLine("Memory Allocated before SqlCommand: " + GC.GetTotalMemory(true));
using (SqlCommand comm = new SqlCommand(sql,conn))
{
Console.WriteLine("Memory Allocated after SqlCommand: " + GC.GetTotalMemory(true));
reference = new WeakReference(comm);
Console.WriteLine("SQL output: " + comm.ExecuteScalar());
Console.WriteLine(
"Memory Allocated before dispose SqlCommand: " + GC.GetTotalMemory(true));
}
GC.Collect();
Console.WriteLine("Memory Allocated after SqlCommand: " + GC.GetTotalMemory(true));
Console.WriteLine("Reference is alive: " + reference.IsAlive);
Console.ReadLine();
}
令我惊讶的是这是我得到的输出:
Memory Allocated before SqlCommand: 236384
Memory Allocated after SqlCommand: 239160
SQL output: (whatever)
Memory Allocated before dispose SqlCommand: 246416
Memory Allocated after dispose SqlCommand: 246548 <– It’s gone up!?
Reference is alive: True <– Why is reference still alive?
起初我可能虽然我的WeakReference可能以某种方式保持命令活着,但我评论了代码,但我得到了类似的结果.
为什么命令不在这里被垃圾收集,即使明确调用了GC.Collect()?如果在using块中引入了变量,我们可以期望该变量有资格进行垃圾收集吗?
解决方法:
处置对象与垃圾收集无关.垃圾收集与清理托管资源有关.处置是为了清理GC未跟踪的非托管资源.
有时,这些非托管资源是显式分配的内存,无需通过GC,有时它们会锁定文件句柄,数据库连接,网络套接字或任何其他可能性.但无论它们是什么,它们都非常明确地不会是GC跟踪的记忆,这就是你所测量的.
至于计算差异,您的差异只是在程序的噪音水平内.您的更改不会影响使用的托管内存量,并且您看到的差异与使用垃圾回收的程序中内存的正常波动一致.
内容总结
以上是互联网集市为您收集整理的c# – 垃圾收集和使用 – 为什么在使用{}`块后没有释放内存?全部内容,希望文章能够帮你解决c# – 垃圾收集和使用 – 为什么在使用{}`块后没有释放内存?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。