在 C# 中显式释放内存 [英] Explicitly freeing memory in c#

查看:33
本文介绍了在 C# 中显式释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 c# 应用程序,它使用了 150mb 的内存(私有字节),主要是由于一个大字典:

I've create a c# application which uses up 150mb of memory (private bytes), mainly due to a big dictionary:

Dictionary<string, int> Txns = new Dictionary<string, int>();

我想知道如何释放这个内存.我试过这个:

I was wondering how to free this memory up. I've tried this:

Txns = null;
GC.Collect();

但它似乎对我的私人字节没有太大影响 - 它们从 155mb 下降到 145mb.有什么线索吗?

But it doesn't seem to make much of a dent in my private bytes - they drop from say 155mb to 145mb. Any clues?

谢谢

-编辑-

好的,我对这段代码的运气更好(它使私有字节减少到 50mb),但为什么呢?

Okay I'm having more luck with this code (it gets the private bytes down to 50mb), but why?

Txns.Clear(); // <- makes all the difference
Txns = null;
GC.Collect();

-编辑-

对于那些说不要使用 GC.collect"的人来说,这很公平(我不打算争论这个,除了说你可以看到我的 C 背景通过),但它并没有真正回答我的问题:为什么垃圾收集器只在我先清除事务列表时才释放内存?既然字典已经被解引用了,它不应该释放内存吗?

Okay for everyone who says 'don't use GC.collect', fair enough (I'm not going to debate that, other than saying you can see my C background coming through), but it doesn't really answer my question: Why does the garbage collector only free the memory if i clear the transaction list first? Shouldn't it free the memory anyway, since the dictionary has been dereferenced?

推荐答案

私有字节反映进程的内存使用情况.当对象被收集时,相关的内存段可能会或可能不会释放给操作系统.CLR 在操作系统级别管理内存,并且由于分配和释放内存不是免费的,因此没有理由立即释放每块内存,因为应用程序稍后可能会请求更多内存.

Private bytes reflect the process' memory usage. When objects are collected the associated memory segment may or may not be freed to the OS. The CLR manages memory at the OS level and since allocating and freeing memory isn't free there's no reason to free each piece of memory immediately as chances are that the application will probably request more memory later.

这篇关于在 C# 中显式释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆