Skip to content

Instantly share code, notes, and snippets.

@detroitpro
Created April 27, 2010 18:38
Show Gist options
  • Save detroitpro/381122 to your computer and use it in GitHub Desktop.
Save detroitpro/381122 to your computer and use it in GitHub Desktop.
public sealed class Mediator
{
private static readonly Mediator _instance = new Mediator();
private Dictionary<MediatedEvent, List<Action<EventArgs>>> _handlers;
/// <summary>
/// Thread-safe synchronization lock.
/// </summary>
private volatile Object _syncLock = new Object();
private Mediator()
{
// Prevent direct instantiation
}
public static void Notify(MediatedEvent mediatedEvent, EventArgs args)
{
_instance.NotifyInternal(mediatedEvent, args);
}
public static void Register(MediatedEvent mediatedEvent, Action<EventArgs> handler)
{
_instance.RegisterInternal(mediatedEvent, handler);
}
public static void Unregister(MediatedEvent mediatedEvent, Action<EventArgs> handler)
{
_instance.UnregisterInternal(mediatedEvent, handler);
}
private List<Action<EventArgs>> GetHandlersForEvent(MediatedEvent key)
{
// Delayed instantiated means we don't create the dictionary unless we actually make use of the class
if (_handlers == null)
{
lock (_syncLock)
{
if (_handlers == null) _handlers = new Dictionary<MediatedEvent, List<Action<EventArgs>>>();
}
}
List<Action<EventArgs>> value;
if (!_handlers.TryGetValue(key, out value))
{
value = new List<Action<EventArgs>>(1);
_handlers[key] = value;
}
return value;
}
private void NotifyInternal(MediatedEvent evt, EventArgs args)
{
List<Action<EventArgs>> handlers = GetHandlersForEvent(evt);
foreach (var handler in handlers)
{
// Do we need this???
//System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => handler.Invoke(args));
handler.Invoke(args);
}
}
private void RegisterInternal(MediatedEvent evt, Action<EventArgs> handler)
{
List<Action<EventArgs>> handlers = GetHandlersForEvent(evt);
handlers.Add(handler);
}
private void UnregisterInternal(MediatedEvent evt, Action<EventArgs> handler)
{
List<Action<EventArgs>> handlers = GetHandlersForEvent(evt);
handlers.Remove(handler);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment