在 C# 中强制垃圾回收的最佳实践 [英] Best Practice for Forcing Garbage Collection in C#

查看:43
本文介绍了在 C# 中强制垃圾回收的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的经验,似乎大多数人会告诉您强制进行垃圾回收是不明智的,但在某些情况下,您正在处理的大对象并不总是在 0 代中被回收,但内存是问题,可以强制收集吗?是否有这样做的最佳实践?

In my experience it seems that most people will tell you that it is unwise to force a garbage collection but in some cases where you are working with large objects that don't always get collected in the 0 generation but where memory is an issue, is it ok to force the collect? Is there a best practice out there for doing so?

推荐答案

最佳做法是不要强制进行垃圾回收.

The best practise is to not force a garbage collection.

根据 MSDN:

"可以强制垃圾通过调用 Collect 来收集,但是大多数时候,这应该是避免,因为它可能会产生性能问题."

"It is possible to force garbage collection by calling Collect, but most of the time, this should be avoided because it may create performance issues. "

但是,如果您可以可靠地测试您的代码以确认调用 Collect() 不会产生负面影响,那么请继续...

However, if you can reliably test your code to confirm that calling Collect() won't have a negative impact then go ahead...

当您不再需要对象时,请确保将其清理干净.如果您有自定义对象,请查看使用using 语句"和 IDisposable 接口.

Just try to make sure objects are cleaned up when you no longer need them. If you have custom objects, look at using the "using statement" and the IDisposable interface.

这个链接有一些关于释放内存/垃圾收集等的很好的实用建议:

This link has some good practical advice with regards to freeing up memory / garbage collection etc:

http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx

这篇关于在 C# 中强制垃圾回收的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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