为了进行简单的模块间通信,存在经典的.NET事件,但是现在事件太多了,并且有一系列事件通过模块相互调用。

Event_A一样触发触发Event_BEvent_C
EventAggregator非常方便在一个模块中进行解耦通信,因此我尝试了
里面有一个EventAggregator的小“Jon Skeet Singleton IV”打破了这些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来发布事件并
对那些事件感兴趣的所有其他模块都可以愉快地处理它们。
没有更多的链接。

但是我会遇到多线程问题吗? 其他模块具有不同的线程,我想在其中发布事件。分派(dispatch)应该不是问题。
我应该在公共(public)方法中使用lock吗?

我不能说这些方法是否是线程安全的,也找不到关于它的文档。

最佳答案

EventAggregator已经锁定,因此您的GlobalEventAggregator不需要。
http://caliburnmicro.codeplex.com/SourceControl/latest#src/Caliburn.Micro/EventAggregator.cs

无关,但推荐的访问单例的方法是通过DI

09-16 12:58