为了进行简单的模块间通信,存在经典的.NET
事件,但是现在事件太多了,并且有一系列事件通过模块相互调用。
像Event_A
一样触发触发Event_B
的Event_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。