Search code examples
c#memory-leakseventhandler

Is the following code in c# cause memory leak issue?


I was wondering if the following code create a memory leak:

using System;

namespace ConsoleApplicationTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            CreateMemoryLeak();
            
            // Some other code here that make the application run longer...
        }

        private static void CreateMemoryLeak()
        {
            new Foo();
        }
    }

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

        public Foo()
        {
            bar.MyEventHandler += SomeMethod;
        }

        private void SomeMethod(object sender, EventArgs e)
        {
            // Put some pretty yet irrelevant code here...
        }
    }

    public class Bar
    {
        public EventHandler MyEventHandler;
    }
}

From my understanding of how EventHandler work, calling CreateMemoryLeak() will create a memory leak, since Foo will not be garbage collected as long a Bar is "alive" or has a reference to Foo via his EventHandler and Bar will not be garbage collected, because it is living inside the instance of Foo. Is my understanding correct, or will be garbage collected, even though the Bar.MyEventHandler has a reference to it. And if it is not a memory, how so ?

Thank you


Solution

  • .net garbage collector does not count references, it checks reachability of the objects from the fixed list of root points. So, circular references is not a problem at all. For your sample both instances of Foo & Bar become unreachable after CreateMemoryLeak end. So, both will be collected on the next GC run, despite they referencing each other. More details https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals#memory-release