嗯..不知道如果我理解正確。那樣的事情呢?使用模式
public void handleui(dynamic s)
{
Application.Current.Dispatcher.Invoke(delegate
{
btn1.Content = s.ToString();
});
}
Globals.Events["error"] += msg=> Console.WriteLine(msg);//logger perhaps
Globals.Events["productb"] += handleui;//sub
Globals.Events["productb"] -= handleui;//unsub
Globals.Events["productb"].Send("productbdata");//raise the event or publish to productb channel subscribers
Globals.Events.Send("broadcast?");
我會想象你可以做一個單一的過濾器,只需將所有事件活動[「產品A」],事件[「產品B」],事件[「productc」]等,以及部分可以當他們想要它時,只需要sub/unsub。
執行。
using System;
using System.Collections.Concurrent;
public class Globals
{
public static MsgBus Events = new MsgBus();
}
public class MsgBus
{
private readonly ConcurrentDictionary<dynamic, MsgChannel> channels = new ConcurrentDictionary<dynamic, MsgChannel>();
public MsgChannel this[dynamic channel]
{
set { channels[channel] = value; }
get
{
var ch = (MsgChannel)channels.GetOrAdd(channel, new MsgChannel());
return ch;
}
}
private MsgChannel broadcast = new MsgChannel();
public void Send(dynamic msg)
{
broadcast.Send(msg);
}
public static MsgBus operator +(MsgBus left, Action<dynamic> right)
{
left.broadcast += right;
return left;
}
public static MsgBus operator -(MsgBus left, Action<dynamic> right)
{
left.broadcast -= right;
return left;
}
}
public class MsgChannel
{
ConcurrentDictionary<Action<dynamic>, int> observers = new ConcurrentDictionary<Action<dynamic>, int>();
public void Send(dynamic msg)
{
foreach (var observer in observers)
{
for (int i = 0; i < observer.Value; i++)
{
observer.Key.Invoke(msg);
}
}
}
public static MsgChannel operator +(MsgChannel left, Action<dynamic> right)
{
if (!left.observers.ContainsKey(right))
{
left.observers.GetOrAdd(right, 0);
}
left.observers[right]++;
return left;
}
public static MsgChannel operator -(MsgChannel left, Action<dynamic> right)
{
if (left.observers.ContainsKey(right) &&
left.observers[right] > 0)
{
left.observers[right]--;
int dummy;
if (left.observers[right] <= 0) left.observers.TryRemove(right, out dummy);
}
return left;
}
}
@aaronburro,你看過DDS嗎?它是否符合您的需求? – 2013-03-05 07:46:55
我看了一下,但這遠遠超出了我可以使用的更重的解決方案。處理所有這些數據的單獨服務需要完全重寫現有的公司消息傳遞基礎結構,這是不可行的,除非我錯過了某些東西。不過,我欣賞這個建議。 – aaronburro 2013-03-05 23:47:54
我不認爲您可以通過駐留在應用程序中的第三方解決方案達到您想要的效果,而無需更改您的基礎架構API和實施。祝你好運。 – 2013-03-06 05:16:07