I need to remove the handler

The more I delve into C # and GC, I find more and more things that I'm not quite sure about. I always thought that Dispose and the corresponding Finalizer are only necessary if there are some unmanaged resources in my classes.

But I have many cases where there are only native C # classes, where I do not quite understand if I need Dispose and the corresponding Finalizer. For example, when I have event handlers attached to my events.

Do I need to remove event handlers when calling Dispose. I was also told that the object might not receive if the event handlers are still connected. If so, then the GC is somehow compromised.

Can I summarize when and how I need to implement Dispose and Finalizer?

Actually I have more questions about this, but maybe the answer to this question may help me further.

+4
source share
1 answer

To clarify your general question about when to do Dispose and Finalize:

If you have a field in your class, this IntPtr(or some other unmanaged resource, but IntPtris the most common), and your classes are responsible for cleaning this resource, then you need to implement a finalizer. In this finalizer, you must release any resource you point to IntPtr. If you do not have IntPtr, then the class you are holding must handle its own finalization and will implement it IDisposeable(see next part)

, IDisposable, , IDisposable dispose Dispose() .

. , , , .

, , ...

, . , null .

public sealed class Example : IDisposable 
{
    public EventHandler MyEvent;

    public void Dispose()
    {
        MyEvent = null;
    }
}

EDIT: , Hans Passant : , , . SafeHandle . , IDisposable, .Dispose().

+3

All Articles