开发者

what happens to events after the object it references is disposed of?

开发者 https://www.devze.com 2023-03-28 19:40 出处:网络
what happens if i link a method of some object to a delegate, and then dispose of the object? Like this:

what happens if i link a method of some object to a delegate, and then dispose of the object?

Like this:

class Hun开发者_开发百科ter
{
    public event Action Shoot;

    public execute()
    {
        Form formBabySeal = new Form();

        Shoot += formBabySeal.Close;

        formBabySeal.Show();
        formBabySeal.Close(); //Dispose Form

        if (Shoot != null)
        {
             Shoot(); //event is null?
        }
    }
}


formBabySeal is not null just because you dispose it. So, formBabySeal.Close() will be called.

Your code is equivalent to this when looking at what methods are called:

Form formBabySeal = new Form();

formBabySeal.Show();
formBabySeal.Close(); //Dispose Form
formBabySeal.Close();

This will close the form (first call to Close) and the second call won't do anything, because the form is already closed.

However, as Steve points out in the comment section, your code will introduce a memory leak, because Shoot still holds a reference to the Close method of formBabySeal and because of this formBabySeal will be kept alive as long as the instance of the class Hunter is alive.


WinDBG with SOS extensions has a way to show GCRoot of any object. This might give you more clues.

0

精彩评论

暂无评论...
验证码 换一张
取 消