Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Event handler subscription management

I have a class:

public abstract class BaseComponent { ... }

Within the constructor of that class we subscribe to an event handler e.g.

protected ObjectWithEventHandler eventObject { get; private set; }

public BaseComponent (ObjectWithEventHandler obj)
{
    eventObject = obj;
    eventObject.ChangedEvent += new EventHandler(eventObject_OnChangedEvent );
}

protected void eventObject_OnChangedEvent (object sender, EventArgs e) { ... }

Are there any hard and fast rules when it comes to EventHandler subscription & unsubscription?

Is it considered good practice to provide some clean-up code that unsubscribes the function from the EventHandler? I.e. implement IDisposable and unsubscribe from the EventHandler then?

Or am I worrying unduly?

like image 273
TK. Avatar asked Oct 28 '25 09:10

TK.


2 Answers

If you have full control of the usage of BaseComponent and you know that EventObject's lifecycle is shorter or equal* with regard to BaseComponent's lifecycle, you can skip unsubscription code.

In all other cases I would include it. In this case implementing IDisposable is good style.

*) effectively, you are coupling eventObject's lifetime to BaseComponent, so it cannot live shorter, but it could still be equal when the two go out of scope together.

like image 71
flq Avatar answered Oct 30 '25 00:10

flq


As long as object which exposes event (eventObject) is created inside a BaseComponent class - you can ignore explicit unsubscribing because it will be GCed automatically but explicit unsubscribe is a good practice anyway.

But if you're subscribing for event which exposed by an external object injected into BaseComponent you should implement IDisposable in the BaseComponent class and in the Dispose() method do cleanup.

like image 31
sll Avatar answered Oct 29 '25 23:10

sll