c# - Jon Skeet 单例和 EventAggregator

标签 c# multithreading events caliburn.micro eventaggregator

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

比如 Event_A 触发 Event_B 触发 Event_C

EventAggregator 对于一个模块中的解耦通信非常方便,所以我尝试了 带有 EventAggregator 的小“Jon Skeet Singleton IV”可以打破那些 event 链。 Jon Skeet on C# singletons can be found here

他说它是线程安全的,但他的例子只是公开了一个单例资源。

这是我的代码

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 来发布事件和 对这些事件感兴趣的每个其他模块都可以愉快地处理它们。 不再有链接。

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

我无法判断这些方法是否是线程安全的,也找不到相关文档。

最佳答案

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

有点不相关,但推荐的访问单例的方法是通过 DI .

关于c# - Jon Skeet 单例和 EventAggregator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21762672/

相关文章:

c# - 有没有办法在 C# (ASP.NET MVC3) 中更改请求的时区?

c# - 这是 C# SqlDecimal 数学错误吗?

c# - 从 DbCommandDefinition 获取 CommandText

java - 为什么线程的恢复和挂起方法应该同步?

c# - Azure 表存储过期

java - 多线程性能

java - 为什么 DelayQueue 没有默认的 Delayed java 实现?

c# - 使用新处理程序附加事件处理程序与直接分配它

c# - 以编程方式解除事件处理程序的 Hook

java - 用于暂停操作的信号量,不限制并发操作