Question about Event handlers and GC

  • Thread starter Thread starter Aamir Mahmood
  • Start date Start date
A

Aamir Mahmood

Hi all,
Consider the following code as just an example to understand what I want to
say.

My question is if a class instance subscribes one or more events of another
class. If that instance which implements the event handler goes out of
scope, what will happen to the instance? Will it be eventually freed by the
GC? Or will it never be freed because its reference is added in the list of
event handlers by other class.


public class EventRaisingClass {
public delegate void SomeEventDelegate(object sender);
public event SomeEventDelegate OnSomeEvent;


public void UserMethod() {
EventHandlerClass ehc = new EventHandlerClass();
this.OnSomeEvent += new SomeEventDelegate(ehc.SomeEventHandler);
}
}

public class EventHandlerClass {
public void SomeEventHandler(object sender) {
// do something
}
}
 
Hi Aamir.

This is a non-problem and you almost answered your own question.
As the delegate holds a reference to the implementing instance, that
instance cannot go out of scope.

Regards
- Michael S
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top