Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.