2014-02-13 56 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

这是我如何在一个模块中完成的。这里的问题是,我想给出许多模块来进行通信。 –