在C#中明确释放内存明确、内存

由网友(孤獨成癮)分享简介:我已经创建一个C#应用程序,它利用了内存(专用字节)150MB,主要是由于大辞典:I've create a c# application which uses up 150mb of memory (private bytes), mainly due to a big dictionary:Dictionary...

我已经创建一个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?

感谢

-edit -

-edit-

好吧我有更多的运气与此code(它得到了专用字节到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();

-edit -

-edit-

好大家谁说'不要使用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?

推荐答案

专用字节反映进程的内存使用情况。当被收集的对象相关联的存储器段可能或可能不被释放到OS中。在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.

阅读全文

相关推荐

最新文章