Created
September 8, 2012 16:15
-
-
Save davybrion/3676624 to your computer and use it in GitHub Desktop.
Code snippets for "Why you should always unsubscribe event handlers" post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Publisher | |
{ | |
public event EventHandler MyEvent; | |
public void FireEvent() | |
{ | |
if (MyEvent != null) | |
{ | |
MyEvent(this, EventArgs.Empty); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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