-
-
Save thomaslevesque/fc8e141f377967c0fcfe to your computer and use it in GitHub Desktop.
This file contains 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
void Main() | |
{ | |
var pub = new Publisher(); | |
var sub = new Subscriber(); | |
sub.Subscribe(pub); | |
GC.Collect(); | |
GC.WaitForPendingFinalizers(); | |
pub.Raise(); | |
// Ensure subscriber isn't collected too early | |
GC.KeepAlive(sub); | |
} | |
class Publisher | |
{ | |
private readonly WeakEventSource<EventHandler> _foo = new WeakEventSource<EventHandler>(); | |
public event EventHandler Foo | |
{ | |
add { _foo.Subscribe(value); } | |
remove { _foo.Unsubscribe(value); } | |
} | |
public void Raise() | |
{ | |
_foo.Raise(this, EventArgs.Empty); | |
} | |
} | |
class Subscriber | |
{ | |
public void Subscribe(Publisher pub) | |
{ | |
pub.Foo += OnFoo; | |
} | |
private void OnFoo(object sender, EventArgs e) | |
{ | |
Console.WriteLine("Subscriber.OnFoo"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment