Yes, thatโs a very good idea. The event publisher has a link to the event subscriber that will prevent the collection of the subscriber from garbage. (See Event Handlers Stop Garbage Collection? )
In addition, if event handlers use the resources that you release, event handlers (which will be referred to as the event publisher) may throw exceptions when resources are released.
Therefore, it is important to unregister any events before , freeing your resources, especially if you use async or several threads, since it is possible in some scenarios for an event raised between freeing a resource and unregistering from this event.
The following code demonstrates this:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReleaseEvents { class Program { public static event EventHandler SomethingHappened; static void Main( string[] args ) { using ( var l_dependent = new Dependent() ) { SomethingHappened( null, EventArgs.Empty ); }
The second time the SomethingHappened event is raised, the Dependent class will throw an InvalidOperationException. You must unregister the event so that this does not happen:
class Dependent : IDisposable {
I really ran into this problem when I first tried to implement the MVVM architecture. When I switched between ViewModels, I just freed what I considered to be my only link (ActiveViewModel property). I did not understand that the events that my ViewModel was subscribed to were stored in memory. As the application ran longer, it became slower and slower. In the end, I realized that the ViewModels, which I thought I released, actually continue to handle events (expensively). I had to explicitly free event handlers in order to fix this problem.
Jdb
source share