[英]Garbage collection and references C#
I have a design and I am not sure if garbage collection will occur correctly. 我有一个设计,我不确定垃圾收集是否会正确发生。
I have some magic apples, and some are yummy some are bad. 我有一些神奇的苹果,有些是美味的,有些是坏的。
I have a dictionary : BasketList = Dictionary <basketID,Basket>
我有一本字典:
BasketList = Dictionary <basketID,Basket>
(list of baskets). (篮子清单)。
Each Basket
object has a single Apple
in it and each Basket
stores a reference to an object AppleSeperation
. 每个
Basket
对象中都有一个Apple
,每个Basket
存储一个对象AppleSeperation
的引用。
AppleSeperation
stores 2 dictionaries, YummyApples = <basketID,Apple>
and BadApples = Dictionary<basketID,Apple>
, so when I'm asked where an apple is I know. AppleSeperation
存储2个词典, YummyApples = <basketID,Apple>
和BadApples = Dictionary<basketID,Apple>
,所以当我被问到苹果在哪里时我知道。
An Apple
object stores BasketsImIn = Dictionary<ID,Basket>
, which points to the Basket and in Shops, and the Apple in Basket. Apple
对象存储BasketsImIn = Dictionary<ID,Basket>
,它指向Basket和Shops,以及Apple in Basket。
My question is, if I delete a basket from BasketList
and make sure I delete the Apple from BadApples
and/or YummyApples
, will garbage collection happen properly, or will there be some messy references lying around? 我的问题是,如果我从
BasketList
删除一个篮子并确保我从BadApples
和/或YummyApples
删除Apple, BadApples
垃圾收集是否会正常发生,或者是否会有一些混乱的引用?
You are right to be thinking carefully about this; 你仔细思考这个问题是正确的; having the various references has implications not just for garbage collection, but for your application's proper functioning.
拥有各种引用不仅对垃圾收集有影响,而且对您的应用程序的正常运行有影响。
However, as long as you are careful to remove all references you have set, and you don't have any other free-standing variables holding onto the reference, the garbage collector will do its work. 但是,只要您小心删除已设置的所有引用,并且没有任何其他独立变量保留引用,垃圾收集器就会完成其工作。
The GC is actually fairly sophisticated at collecting unreferenced objects. GC在收集未引用的对象时实际上相当复杂。 For example, it can collect two objects that reference each other, but have no other 'living' references in the application.
例如,它可以收集两个相互引用的对象,但在应用程序中没有其他“活动”引用。
See http://msdn.microsoft.com/en-us/library/ee787088.aspx for fundamentals on garbage collection. 有关垃圾回收的基础知识,请参见http://msdn.microsoft.com/en-us/library/ee787088.aspx 。
From the above link, when garbage collection happens... 从上面的链接,当垃圾收集发生时......
If you are performing the clean-up properly, then you need not worry! 如果您正在进行正确的清理,那么您不必担心!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.