using Quasar.Common.Networking; using System.Collections.Generic; using System.Linq; namespace Quasar.Common.Messages { /// /// Handles registrations of s and processing of s. /// public static class MessageHandler { /// /// List of registered s. /// private static readonly List Processors = new List(); /// /// Used in lock statements to synchronize access to between threads. /// private static readonly object SyncLock = new object(); /// /// Registers a to the available . /// /// The to register. public static void Register(IMessageProcessor proc) { lock (SyncLock) { if (Processors.Contains(proc)) return; Processors.Add(proc); } } /// /// Unregisters a from the available . /// /// public static void Unregister(IMessageProcessor proc) { lock (SyncLock) { Processors.Remove(proc); } } /// /// Forwards the received to the appropriate s to execute it. /// /// The sender of the message. /// The received message. public static void Process(ISender sender, IMessage msg) { IEnumerable availableProcessors; lock (SyncLock) { // select appropriate message processors availableProcessors = Processors.Where(x => x.CanExecute(msg) && x.CanExecuteFrom(sender)).ToList(); // ToList() is required to retrieve a thread-safe enumerator representing a moment-in-time snapshot of the message processors } foreach (var executor in availableProcessors) executor.Execute(sender, msg); } } }