How to follow a publisher/subscriber strategy in C# or .NET?
What is the most suitable language construct in C# or class or function in .NET's BCL to follow a publisher/subscr开发者_高级运维iber (aka. signals/slots) strategy?
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.
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
精彩评论