Abbas
Abbas

Reputation: 5044

Adding and Removing Event Handler in .net

i recently created a sample application, wherein i implemented the events and delegates, when the Properties value is changed this event will raise, i have a question regarding events

  1. Does event objects are created in memory? or they are just static object which gets removed once the event is fired?

  2. Is it necessary to remove the handler once the event is executed, to free-up resources. does removing handler once done, boost's up the application performance, i am talking about the application which are using lots of events

Upvotes: 1

Views: 1008

Answers (3)

Royi Namir
Royi Namir

Reputation: 148524

events are like delegates ( with another layer of protection) .

when you register to an event - you are actually making a reference to another object.

this object can't go through GC because you made a reference to it !

it isnt "un-referenced".

but your object CAN go through GC. ( if un-referenced).

so you end up with memory leak.

you should manually remove the reference .

Upvotes: 0

Simon Wilson
Simon Wilson

Reputation: 10424

  1. Events can be both static and instance bound. Subscribers to the event are never removed while the event broadcaster is alive, unless implicitly done so, usually with the -= operator.

  2. Yes, yes and yes. If you don't clean-up your subscribers you have a memory-leak waiting to happen.

If all this is a concern to you perhaps you could look into the WeakEvent pattern.

Upvotes: 1

Raj Ranjhan
Raj Ranjhan

Reputation: 3917

Events do take memory and are not garbage collected until after you unsubscribe from them. They are a common cause of memory leaks.

Upvotes: 1

Related Questions