MStodd
MStodd

Reputation: 4746

Event unsubscription memory leak due to exception

I didn't want to go through all the event unsubscription memory leak posts to see if any dealt with exceptions, so I'm making a new post.

If I register a function with an event and an exception occurs before I unregister, will that cause a memory leak? I have a try/catch in the calling function, but not in the function where I wire/unwire the event, and would rather not have a try/catch if I don't need it.

Upvotes: 0

Views: 80

Answers (1)

supercat
supercat

Reputation: 81159

With most subscription methods, an event subscriber who does not unsubscribe will have his lifetime extended to that of the event source. If the event source is short-lived, this will not be a problem. If the event source is long-lived, this can be a huge problem. The best idiom is generally to unwire events in IDisposable. If one uses a "using" block, the Dispose method will get called, ensuring the events get unsubscribed.

Upvotes: 1

Related Questions