在我的几个项目中,很明显我需要一些比标准 .NET 事件更强大的东西。
基本上,我想要在消息泵中的选项,当他们感兴趣的组件发生变化时,向特定订阅者提出回调(事件)。
这可能是一个项目的特定 I/O 更改状态(例如按钮闭合触点),或者是从无线以太网接收到的针对另一个项目的特定 MAC 地址的消息。
我目前的思路是使用字典,以及针对每个地址的代表列表(对于此示例)。
我还没有调试过这个,但以下是正确的吗?
class CustomSubscription
{
public delegate void DataReceivedHandler(object sender, DataReceivedEventArgs args);
public class DataReceivedEventArgs : EventArgs
{
public byte[] data;
}
private readonly Dictionary<int, List<DataReceivedHandler>> _subscribers;
public CustomSubscription()
{
_subscribers = new Dictionary<int, List<DataReceivedHandler>>();
}
public void AddSubscriber(int address, DataReceivedHandler callback)
{
if (false == _subscribers.ContainsKey(address))
{
_subscribers.Add(address, new List<DataReceivedHandler>());
}
_subscribers[address].Add(callback);
}
public void RemoveSubscriber(int address, DataReceivedHandler callback)
{
if (false == _subscribers.ContainsKey(address))
{
return;
}
if (_subscribers[address].Contains(callback))
{
_subscribers[address].Remove(callback);
}
}
public void HandleIncommingData(int address, object sender, byte[] payload)
{
if (false == _subscribers.ContainsKey(address))
{
// Nothing subscribed - take no action
return;
}
// Raise callbacks with all subscribers
foreach (DataReceivedHandler callback in _subscribers[address])
{
callback(sender, new DataReceivedEventArgs
{
data = payload
});
}
}
}