2014-02-13 54 views
6

爲了簡單的模塊間通信,出現了經典的.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嗎?

我不能告訴這些方法是否是線程安全的,並不能找到在該文檔。

+0

您可能想閱讀本文。 [CSharpMessenger](http://wiki.unity3d.com/index.php?title=CSharpMessenger) –

+1

我不是基於字符串的信使系統的粉絲,因爲沒有方便的方法來查找所有發佈者或所有訂閱者事件。使用強類型的消息,您可以輕鬆找到該類型的用法並獲取所需的所有信息。請參閱Galasoft Messenger:http://blog.galasoft.ch/posts/2009/09/mvvm-light-toolkit-messenger-v2/ –

+0

@ L.B感謝您的建議。認爲以前有更多的人遇到過這種問題。也許那個Messanger比我自己的更好。 –

回答

2

EventAggregator已經鎖定,所以你的GlobalEventAggregator不需要。 http://caliburnmicro.codeplex.com/SourceControl/latest#src/Caliburn.Micro/EventAggregator.cs

種類無關,但推薦訪問單身人士的方式是通過DI

+0

這意味着我將有一個全球DI容器的所有模塊? –

+1

caliburn micro proj具有引導程序設置的示例:http://caliburnmicro.codeplex.com/SourceControl/latest#samples/Caliburn.Micro.HelloEventAggregator/Caliburn.Micro.HelloEventAggregator/MEFBootstrapper.cs 這個想法是你註冊引導程序中的eventaggregator和對象通過構造函數或屬性注入自動獲取eventaggregator的實例。 – DeveloperGuo

+0

這是我如何在一個模塊中完成的。這裏的問題是,我想給出許多模塊來進行通信。 –