Unsubscribing from events helps stop unwanted actions and frees memory. It keeps your program clean and fast.
Event unsubscription and memory in C Sharp (C#)
eventSource.EventName -= EventHandlerMethod;
Use the same method you used to subscribe, but with '-=' to unsubscribe.
Unsubscribing is important especially in applications with many events or long lifetimes.
OnSomeEvent from the SomeEvent event.publisher.SomeEvent -= OnSomeEvent;
Button_Click method from running when the button is clicked.button.Click -= Button_Click;
This program shows a publisher sending an event and a subscriber listening. After unsubscribing, the subscriber no longer reacts, which helps avoid memory leaks and unwanted calls.
using System; class Publisher { public event EventHandler? RaiseEvent; public void DoSomething() { Console.WriteLine("Doing something..."); RaiseEvent?.Invoke(this, EventArgs.Empty); } } class Subscriber { public void Subscribe(Publisher pub) { pub.RaiseEvent += HandleEvent; } public void Unsubscribe(Publisher pub) { pub.RaiseEvent -= HandleEvent; } private void HandleEvent(object? sender, EventArgs e) { Console.WriteLine("Event received in subscriber."); } } class Program { static void Main() { Publisher pub = new Publisher(); Subscriber sub = new Subscriber(); sub.Subscribe(pub); pub.DoSomething(); // Event fires, subscriber reacts sub.Unsubscribe(pub); pub.DoSomething(); // Event fires, but subscriber does not react } }
Always unsubscribe from events when the subscriber is no longer needed.
Failing to unsubscribe can cause memory leaks because the publisher keeps a reference to the subscriber.
Use weak event patterns or tools if manual unsubscription is difficult.
Unsubscribing stops event notifications and frees memory.
Use '-=' with the same method to unsubscribe from an event.
Always unsubscribe to avoid memory leaks and unexpected behavior.