Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Delegates cause memory leaks?

Can Delegates cause memory leaks?

I mean, by e.g. if a class A contains a ADelegate and the latter points to the BMethod (of B class) can this prevent the A class or B class collection by the GC?

If so, how can we "free" delegates (setting ADeletate = Nothing / null?)

How do you comment this one:

//Class A Finalize, containing ADelegateInstance as ADelegate'
protected override void Finalize()
{
    ADelegateInstance = 
        (ADelegate)System.Delegate.RemoveAll(
            ADelegateInstance, ADelegateInstance);
    ADelegateInstance = null;
    base.Finalize();
}

'Class A Finalize, containing ADelegateInstance as ADelegate'
Protected Overrides Sub Finalize()
    ADelegateInstance = _ 
        CType(System.Delegate.RemoveAll(ADelegateInstance, ADelegateInstance), _ 
            ADelegate)
    ADelegateInstance = Nothing
    MyBase.Finalize()
End Sub
like image 787
serhio Avatar asked Feb 09 '10 08:02

serhio


1 Answers

Yes, the reference will stay alive unless you unsubscribe from the event:

someObject.SomeEvent -= SomeDelegate;
like image 111
Ed S. Avatar answered Sep 20 '22 18:09

Ed S.