Does the garbage collector collect clear objects that are subscribed to events?

If I do the following:

public class Test
{
    public static void Main()
    {
        List<Person> persons = new List<Person> { new Person() };

        persons[0].Sneezing += new EventHandler(Person_Sneezing);

        persons = null;
    }

    public static void Person_Sneezing(object sender, EventArgs e)
    {
        (sender as Person).CoverFace();
    }
}

Is the person who was personally [0] still exists in memory because the Sneezing delegate has a reference to the Person_Sneezing method or is he going to get a GC?

+5
source share
3 answers

This will be collected by GC. For storage in memory, an object must directly or indirectly refer to ...

  • Value on the stack
  • Value set in strong GC knob
  • A corner case or two that I don't think about right now

This does not apply to an object in individuals [0]. Therefore, it will be assembled.

, , , Person() , ThreadLocalStorage.

+8

; , . , :

public class Test
{
    public void HookupStuff()
    {
        List<Person> persons = new List<Person> { new Person() };

        this.EventHappened += new EventHandler(persons[0].SomeMethod);
        // persons[0].Sneezing += new EventHandler(Person_Sneezing);

        persons = null;
    }
}

persons[0] , persons, .

+6

, , .

, , , "" , , , , "" - , , .. . .

, IDisposable, Dispose, , dispose, .

+1

All Articles