What is the most suitable language construct in C# or class or function in .NET's BCL to follow a publisher/subscriber (aka. signals/slots) strategy?
+7
A:
Events in C# and VB are the typical language construct for handling pub/sub:
public class Publisher
{
public event EventHandler MyEvent;
private void RaiseEvent()
{
EventHandler handler = MyEvent;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
public class Subscriber
{
public void Subscribe(Publisher pub)
{
pub.MyEvent += MethodToCall;
}
private void MethodToCall(object sender, EventArgs e)
{
// This will be called from Publisher.RaiseEvent
}
}
Alternatives include Reactive Extensions and WPF Commanding.
Note that if the Publisher is long-lived but the Subscriber should be short-lived, the Subscriber will need to unsubscribe from the event - otherwise the Publisher will maintain a reference to the Subscriber due to the event, preventing garbage collection.
Jon Skeet
2010-09-10 06:23:00
I would also implement IDisposable on the subscriber to ensure that the -= call is made on MyEvent. Otherwise the Publisher will leak.
Marco
2010-09-10 06:29:16
@Marco: This was only meant to be a demonstration of the syntax really, not a best practices guide. There's a whole heap of things to know about events in reality. Also, in my experience you rarely *actually* need to unsubscribe - it's only if the publisher would otherwise outlive the subscriber, and while that can happen, it's relatively rare in my experience. I'll edit to mention this though.
Jon Skeet
2010-09-10 06:38:17
+1
A:
This Microsoft article may also be useful in that it describes how the Observer design pattern can be implemented using .NET: http://msdn.microsoft.com/en-us/library/ff648108.aspx
Christopher Hunt
2010-09-10 06:41:21