Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 8, 2012 16:15
Show Gist options
  • Save davybrion/3676624 to your computer and use it in GitHub Desktop.
Save davybrion/3676624 to your computer and use it in GitHub Desktop.
Code snippets for "Why you should always unsubscribe event handlers" post
public class Publisher
{
public event EventHandler MyEvent;
public void FireEvent()
{
if (MyEvent != null)
{
MyEvent(this, EventArgs.Empty);
}
}
}
public class BadSubscriber
{
public BadSubscriber(Publisher publisher)
{
publisher.MyEvent += publisher_MyEvent;
}
void publisher_MyEvent(object sender, EventArgs e)
{
Console.WriteLine("the publisher notified the bad subscriber of an event");
}
}
public class GoodSubscriber : IDisposable
{
private readonly Publisher publisher;
public GoodSubscriber(Publisher publisher)
{
this.publisher = publisher;
publisher.MyEvent += publisher_MyEvent;
}
void publisher_MyEvent(object sender, EventArgs e)
{
Console.WriteLine("the publisher notified the good subscriber of an event");
}
public void Dispose()
{
publisher.MyEvent -= publisher_MyEvent;
}
}
static void Main(string[] args)
{
var publisher = new Publisher();
var badSubscriber = new BadSubscriber(publisher);
var goodSubscriber = new GoodSubscriber(publisher);
var badSubscriberRef = new WeakReference(badSubscriber);
var goodSubscriberRef = new WeakReference(goodSubscriber);
publisher.FireEvent();
badSubscriber = null;
goodSubscriber.Dispose();
goodSubscriber = null;
GC.Collect();
Console.WriteLine(goodSubscriberRef.IsAlive ? "good publisher is alive" : "good publisher is gone");
Console.WriteLine(badSubscriberRef.IsAlive ? "bad publisher is alive" : "bad publisher is gone");
publisher.FireEvent();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment