Garbage collection and references C#

2019-05-30 02:56发布

问题:

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>
(list of baskets).

Each Basket object has a single Apple in it and each Basket stores a reference to an objectAppleSeperation.

AppleSeperation stores 2 dictionaries, YummyApples = <basketID,Apple> and BadApples = Dictionary<basketID,Apple>, so when I'm asked where an apple is I know.

An Apple object stores BasketsImIn = Dictionary<ID,Basket>, which points to the Basket and in Shops, and the 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?

回答1:

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. For example, it can collect two objects that reference each other, but have no other 'living' references in the application.



回答2:

See http://msdn.microsoft.com/en-us/library/ee787088.aspx for fundamentals on garbage collection.

From the above link, when garbage collection happens...

  1. The system has low physical memory.
  2. The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This means that a threshold of acceptable memory usage has been exceeded on the managed heap. This threshold is continuously adjusted as the process runs.
  3. The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

If you are performing the clean-up properly, then you need not worry!