Frage

I have a class that holds on to a list of unmanaged resources. These should be cleaned up in the finalizer, to make sure nothing is leaked. However, they are contained in a List<IntPtr>. I have a couple of questions to this situation:

  • Am I correct in assuming it is unsafe to enumerate the list in the finalizer, because it is possible that the list has already been garbage collected?
  • Is the only other way to wrap each individual resource in a class that implements a finalizer, thus adding a much larger pressure on the garbage collector? And then the list would store this class?
War es hilfreich?

Lösung 2

I found the answer here: https://stackoverflow.com/a/20167998/553294. Here supercat states that:

If an object has an active finalizer, then if the GC would collect it (but for the existence of the finalizer), the GC will instead add it to a queue of objects whose finalizers should be run ASAP and, having done so, de-activate it. The reference within the queue will prevent the GC from collecting the object until the finalizer has run; once the finalizer finishes, if no other references exist to the object and it hasn't re-registered its finalizer, it will cease to exist.

So an object is considered reachable while in the finalization queue, which means the inner list is considered reachable as well. Thus, it is safe to access the list from the finalizer.

Andere Tipps

Just a quick note about Finalize Guidelines

An object's Finalize method should free any external resources that the object owns. Moreover, a Finalize method should release only resources that the object has held onto. The Finalize method should not reference any other objects.

http://msdn.microsoft.com/en-us/library/vstudio/b1yfkh5e(v=vs.100).aspx

Finalize and Dispose guidelines are located toward the bottom of the article

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top