tags:

views:

104

answers:

3

I have a class shown below. Server instance holds reference to listener instance. Listener holds reference to server instance through event delegate. Will this prevent GC from collecting server instance? If so, how to break this cycle? Should I implement IDisposable or override Finalize method or do something else?

public class Server
    {        
        public Listener Listener { get; private set; }        

        public Server(Listener listener)
        {
            Listener = listener;
            Listener.ClientChannelConnected += new EventHandler<ClientChannelConnectedArgs>(listener_ClientChannelConnected);
        }        

        void listener_ClientChannelConnected(object sender, ClientChannelConnectedArgs e)
        {
            ...
        }
}
+1  A: 

No. The .NET garbage collector is smart enough to resolve circular references.

Jonathan Grynspan
I didnt' know that :(Thanks!
Marko
+1  A: 

Strangely, I found that this type of code consistently leaks in .net, and had to be careful to -= the event handler. It is true that the memory is released eventually, but in practice you want to clean up after yourself sooner than that.

Also, never ever use a lambda expression to handle an event, as you will never have a reference back to that object.

Marco
A: 

Read this article about memory leaks. Sometimes you should use -=.

levanovd