Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jon Skeet Singleton and EventAggregator

For the sake of simple inter-module communication there were classic .NET events, but there are too many right now and there are chains of events calling each other through modules.

Like Event_A triggers Event_B which fires Event_C.

The EventAggregator is very handy for decoupled communication in one module, so I tried the little "Jon Skeet Singleton IV" with an EventAggregator in it to break those event chains. Jon Skeet on C# singletons can be found here

He tells that it is threadsafe, but his example does nothing more than exposing a Singleton resource.

Here is my code

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);
    }
}

Now I could use this GlobalEventAggregator in every module to Publish events and every other module which is interested in those events can happily handle them. No more chaining.

But will I get multithreading issues with that? The other modules have different threads and I want to Publish events in them. The Dispatching should not be a problem. Should I use lock in the public methods?

I cannot tell whether those methods are threadsafe and cannot find documentation on that.

like image 366
Mare Infinitus Avatar asked Feb 13 '14 18:02

Mare Infinitus


1 Answers

EventAggregator already locks so your GlobalEventAggregator won't need to. http://caliburnmicro.codeplex.com/SourceControl/latest#src/Caliburn.Micro/EventAggregator.cs

Kind of unrelated, but the recommended way to access the singleton is through DI.

like image 177
DeveloperGuo Avatar answered Sep 30 '22 10:09

DeveloperGuo