I have a class MyClass
containing an AutoResetEvent
(or a ManualResetEvent
).
public class MyClass
{
private AutoResetEvent _myWaitHandle;
public MyClass()
{
_myWaitHandle = new AutoResetEvent(false);
}
}
In the course of normal events, the program creates a new MyClass
, uses it, and then lets it fall out of scope, with no further uses for the life of the program. However, it never calls the Dispose()
or Close()
method of the AutoResetEvent
, either directly or from a using
block. Per Microsoft, "you should dispose of it either directly or indirectly".
My question is this: does the presence of the not-explicitly-disposed AutoResetEvent
prevent the parent MyClass
object from being marked as eligible for garbage collection?
Short answer: No. The AutoResetEvent
object does not prevent an instance of MyClass
from being garbage collected.
Once the instance of MyClass
is out of scope, no further references to the object remain. Therefore the object is eligible to garbage collection.
The same applies to the instance of AutoResetEvent
stored in _myWaitHandle
with the difference, that a reference to this object is put on the finalization queue of the GC, to call the objects Finalizer before being finally garbage collected.
Even if the AutoResetEvent
would store a reference back to its MyClass
parent object, both objects are eligible to garbage collection, as long as neither one is referenced elsewhere.
For details on the topic of garbage collection, see https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/