Skip to content

Instantly share code, notes, and snippets.

@thomaslevesque
Created August 26, 2015 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomaslevesque/fc8e141f377967c0fcfe to your computer and use it in GitHub Desktop.
Save thomaslevesque/fc8e141f377967c0fcfe to your computer and use it in GitHub Desktop.
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