Question about event handlers and object scope.


K

Ken Varn

If an object of class A adds an event handler to and object of class B, and
class A is finalized, does the handler delegate get removed from class B's
event handler or is there a bad pointer on class B's event handler? In
other words, do I have to put a destructor in class A to remove its event
method from class B's event handler?

Example:

class B
{
public B() { }

public delegate void HandlerDelegate(object sender, EventArgs e);
public event HandlerDelegate SomeEvent;
}

class A
{
public A(B b)
{
b.SomeEvent += new B.HandlerDelegate(MyEventHandler);
}

protected void MyEventHandler(object sender, EventArgs e)
{

}
}



--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.

EmailID = varnk
Domain = Diebold.com
-----------------------------------
 
Ad

Advertisements

N

Nicholas Paldino [.NET/C# MVP]

Ken,

If class B is holding a delegate which points to a method in object A,
then A can not be finalized, because A is still accessible through B. As
long as B is accessible and holds the delegate to the method on the instance
of A, A can not be eligible for GC.

Because of this, if you want A to be eligible for GC, you have to
explicitly remove the event handler from B.

Hope this helps.
 
Ad

Advertisements

K

Ken Varn

Could this be done by adding a destructor for class A and have the
destructor remove the delegate from class B? In know that in this
particular scenario, class B may be finalized before class A, but lets
suppose class B's event member is static.

--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.

EmailID = varnk
Domain = Diebold.com
-----------------------------------
Nicholas Paldino said:
Ken,

If class B is holding a delegate which points to a method in object A,
then A can not be finalized, because A is still accessible through B. As
long as B is accessible and holds the delegate to the method on the instance
of A, A can not be eligible for GC.

Because of this, if you want A to be eligible for GC, you have to
explicitly remove the event handler from B.

Hope this helps.
 

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

Top