假设我想要从MarketDataProvider
类发布一个事件。问题是事件逻辑更深层次。MarketDataProvider
- > Level1SocketClient
- > Level1MessageHandler
。
简而言之,我想提出Level1MessageHandler
MarketDataProvider
可以发布的事件。此处的性能至关重要,因为生成了大量事件。我想找到一种干净的方式来做到这一点,而不是从每个级别链接事件。
答案 0 :(得分:2)
中间类可以将Add和Remove调用传递给最低级别的类,而不是拥有一个Event本身吗?即
public class Level1MessageHandler
{
public event EventHandler<MessageEventArgs> MessageReceived;
}
public class Level1SocketClient
{
Level1MessageHandler level1Handler;
public event EventHandler<MessageEventArgs> MessageReceived
{
add
{
level1Handler.MessageReceived += value;
}
remove
{
level1Handler.MessageReceived -= value;
}
}
}
这至少会削减一级代表电话。
(或者我的调用方向是否被颠倒?无论如何,我认为这个想法很明确。)
更新
出现了一个有趣的问题:如果中间监听器需要是一次性的,并且在处理时,会删除通过它添加的所有事件,会发生什么?您可以通过记录在本地事件中添加的事件来实现,如下所示:
public interface IMessagePublisher<TEventArgs> where TEventArgs : EventArgs
{
event EventHandler<TEventArgs> MessageReceived;
}
public class MessageRePublisher<TEventArgs> : IMessagePublisher<TEventArgs>, IDisposable where TEventArgs : EventArgs
{
readonly IMessagePublisher<TEventArgs> publisher;
public MessageRePublisher(IMessagePublisher<TEventArgs> publisher)
{
this.publisher = publisher;
}
EventHandler<TEventArgs> messageReceivedEventsAdded = null;
public event EventHandler<TEventArgs> MessageReceived
{
[MethodImpl(MethodImplOptions.Synchronized)]
add
{
// events are multicast delegates, which are immutable. We need to remove the previous
// combined event, create a new combined event, then added that.
// More here: http://msdn.microsoft.com/en-us/magazine/cc163533.aspx
if (messageReceivedEventsAdded != null)
publisher.MessageReceived -= messageReceivedEventsAdded;
messageReceivedEventsAdded += value;
if (messageReceivedEventsAdded != null)
publisher.MessageReceived += messageReceivedEventsAdded;
}
[MethodImpl(MethodImplOptions.Synchronized)]
remove
{
if (messageReceivedEventsAdded != null)
publisher.MessageReceived -= messageReceivedEventsAdded;
messageReceivedEventsAdded -= value;
if (messageReceivedEventsAdded != null)
publisher.MessageReceived += messageReceivedEventsAdded;
}
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (messageReceivedEventsAdded != null && publisher != null)
{
publisher.MessageReceived -= messageReceivedEventsAdded;
}
}
messageReceivedEventsAdded = null;
}
#endregion
}
中间监听器将其所有事件组合成一个连接事件,然后每次添加和删除它。