Do i have to unsubscribe from anonymous event handlers of local variables?

后端 未结 3 2185
暖寄归人
暖寄归人 2021-02-20 04:34

If I have a code that looks something like this:

public void Foo()
{
    Bar bar = new Bar();

    bar.SomeEvent += (sender, e) =>
    {
        //Do somethin         


        
3条回答
  •  忘了有多久
    2021-02-20 05:33

    Your situation is fine; the event subscriber will not prevent the publisher from being collected, but the opposite can happen.

    For example,

    class Foo
    {
        public event EventHandler FooEvent;
    
        void LeakMemory()
        {
            Bar bar = new Bar();
    
            bar.AttachEvent(this);
        }
    }
    
    class Bar
    {
        void AttachEvent(Foo foo)
        {
            foo.FooEvent += (sender, e) => { };
        }
    }
    

    In this case, the instance of Bar created within LeakMemory can't be collected until either

    • The anonymous method represented by the lambda is removed from FooEvent's invocation list
    • The instance of Foo to which it's attached can be collected

    This is because the event (which is just some syntactic sugar over an ordinary delegate instance) holds onto a list of delegates to invoke when it's invoked, and each of these delegates has, in turn, a reference to the object that it's attached to (in this case, the instance of Bar).

    Note that we're only talking about collection eligibility here. Just because it's eligible doesn't say anything about when (or even, really, if) it will be collected, just that it can be.

提交回复
热议问题