爲了簡單的模塊間通信,出現了經典的.NET
事件,但現在有太多的事件,並且有事件鏈通過模塊相互調用。Jon Skeet Singleton和EventAggregator
像Event_A
觸發器Event_B
其中的火災Event_C
。
的EventAggregator
是在一個模塊中分離通信非常方便,所以我試圖 小「喬恩斯基特辛格爾頓IV」在它的EventAggregator
打破那些event
鏈。 Jon Skeet on C# singletons can be found here
他說這是線程安全的,但他的例子只是暴露一個Singleton資源。
這裏是我的代碼
public static class GlobalEventAggregator
{
private static readonly IEventAggregator EventAggregator = new EventAggregator();
// tell C# compiler not to mark type as beforefieldinit
static GlobalEventAggregator()
{
}
public static void Subscribe(object instance)
{
EventAggregator.Subscribe(instance);
}
public static void Unsubscribe(object instance)
{
EventAggregator.Unsubscribe(instance);
}
public static void Publish(object message)
{
EventAggregator.Publish(message);
}
}
現在我可以每個模塊中使用此GlobalEventAggregator
來發布事件和 所有其他模塊,感興趣的那些事件能夠愉快地處理它們。 沒有更多的鏈接。
但我會與多線程問題?其他模塊有不同的線程,我想在其中發佈事件。調度不應該是一個問題。 我應該在公共方法中使用lock
嗎?
我不能告訴這些方法是否是線程安全的,並不能找到在該文檔。
您可能想閱讀本文。 [CSharpMessenger](http://wiki.unity3d.com/index.php?title=CSharpMessenger) –
我不是基於字符串的信使系統的粉絲,因爲沒有方便的方法來查找所有發佈者或所有訂閱者事件。使用強類型的消息,您可以輕鬆找到該類型的用法並獲取所需的所有信息。請參閱Galasoft Messenger:http://blog.galasoft.ch/posts/2009/09/mvvm-light-toolkit-messenger-v2/ –
@ L.B感謝您的建議。認爲以前有更多的人遇到過這種問題。也許那個Messanger比我自己的更好。 –