static void Main() { MainWindow form = new MainWindow(); MessagePump.Run(form, () => { }); return; }
/// <summary> /// Runs this game mode client. /// </summary> /// <returns>true if shut down by the game mode, false otherwise.</returns> /// <exception cref="Exception">Thrown if a game mode is already running.</exception> public bool Run() { if (InternalStorage.RunningClient != null) { throw new Exception("A game mode is already running!"); } InternalStorage.RunningClient = this; // Prepare the syncronization context _syncronizationContext = new SampSharpSyncronizationContext(); _messagePump = _syncronizationContext.MessagePump; SynchronizationContext.SetSynchronizationContext(_syncronizationContext); // Initialize the game mode and start the main routine Initialize(); // Pump new tasks _messagePump.Pump(); // Clean up InternalStorage.RunningClient = null; CommunicationClient.Disconnect(); return(_shuttingDown); }
public IEnumerable<IMessagePump> CreateAll() { var openGenericHandlerType = typeof (IHandleRequest<,>); var handlerTypes = _typeProvider.RequestHandlerTypes.ToArray(); // Create a single connection to each request queue determined by routing var allMessageTypesHandledByThisEndpoint = _handlerMapper.GetMessageTypesHandledBy(openGenericHandlerType, handlerTypes); var bindings = allMessageTypesHandledByThisEndpoint .Select(m => new {MessageType = m, QueuePath = _router.Route(m, QueueOrTopic.Queue)}) .GroupBy(b => b.QueuePath) .Select(g => new {QueuePath = g.Key, HandlerTypes = g.SelectMany(x => _handlerMapper.GetHandlerTypesFor(openGenericHandlerType, x.MessageType))}); // Each binding to a queue can handle one or more request types depending on the routes that are defined foreach (var binding in bindings) { var messageTypes = _handlerMapper.GetMessageTypesHandledBy(openGenericHandlerType, binding.HandlerTypes).ToArray(); _logger.Debug("Creating message pump for request queue '{0}' handling {1}", binding.QueuePath, messageTypes.ToTypeNameSummary(selector: t => t.Name)); var messageReceiver = _messagingFactory.GetQueueReceiver(binding.QueuePath); var handlerMap = _handlerMapper.GetHandlerMapFor(openGenericHandlerType, messageTypes); var pump = new MessagePump(_clock, _dispatchContextManager, _logger, _messageDispatcherFactory.Create(openGenericHandlerType, handlerMap), messageReceiver); _garbageMan.Add(pump); yield return pump; } }
/// <summary> /// 添加监听的端口 /// </summary> /// <param name="messagePump"></param> public void AddMessagePump(MessagePump messagePump) { if (messagePump == null) { throw new Exception("BaseWorld.AddMessagePump(...) - messagePump == null error!"); } if (messagePump.World != null) { throw new ArgumentException("BaseWorld.AddMessagePump(...) - messagePump.World != null error!", "messagePump.World"); } m_LockAddMessagePump.Enter(); { // 创建新的MessagePump数组,添加数据,交换数组数据,不需要锁定,没有引用时自动会回收数据 MessagePump[] tempMessagePump = new MessagePump[m_MessagePump.Length + 1]; for (int iIndex = 0; iIndex < m_MessagePump.Length; ++iIndex) { tempMessagePump[iIndex] = m_MessagePump[iIndex]; } tempMessagePump[m_MessagePump.Length] = messagePump; messagePump.World = this; m_MessagePump = tempMessagePump; } m_LockAddMessagePump.Exit(); }
public DelayedDeliveryPump(MsmqMessageDispatcher dispatcher, DueDelayedMessagePoller poller, IDelayedMessageStore storage, MessagePump messagePump, string errorQueue, int numberOfRetries, Action <string, Exception, CancellationToken> criticalErrorAction, TimeSpan timeToWaitForStoreCircuitBreaker, Dictionary <string, string> faultMetadata, TransportTransactionMode transportTransactionMode) { this.dispatcher = dispatcher; this.poller = poller; this.storage = storage; this.numberOfRetries = numberOfRetries; this.faultMetadata = faultMetadata; pump = messagePump; this.errorQueue = errorQueue; txOption = transportTransactionMode == TransportTransactionMode.TransactionScope ? TransactionScopeOption.Required : TransactionScopeOption.RequiresNew; storeCircuitBreaker = new RepeatedFailuresOverTimeCircuitBreaker("DelayedDeliveryStore", timeToWaitForStoreCircuitBreaker, ex => criticalErrorAction("Failed to store delayed message", ex, CancellationToken.None)); }
public ConnectedClient(ClientConfig cfg, IConnector connector) { _cfg = cfg; _messageBuilder = new MessageBuilder(cfg); _connection = new DurableConnection(new InitializingConnector(connector, (session, cancel) => { session.Send(_messageBuilder.Logon()); if (!(session.Receive(cancel).Result is Mantle.Fix44.Logon)) { throw new UnexpectedMessageReceived("Expected Logon"); } if (_cfg.MarketDataSymbols != null) { foreach (string symbol in _cfg.MarketDataSymbols) { session.Send(_messageBuilder.MarketDataRequest(symbol, MessageBuilder.MarketDataType.Order)); session.Send(_messageBuilder.MarketDataRequest(symbol, MessageBuilder.MarketDataType.Trade)); } } })); _messagePump = new MessagePump( _connection, (msg, sessionID) => _scheduler.Schedule( () => OnMessage(msg.Visit(new MessageDecoder(sessionID, _cfg.Extensions))))); _watchdog = new ConnectionWatchdog(_connection, _scheduler, _messageBuilder); }
public static void Initialize( System.Action onDrawCallback, System.Action onCloseCallback, System.Action onSetupCallback ) { onDraw = onDrawCallback; onClose = onCloseCallback; camera = new CameraController(); Instance.InitDevice(); onSetupCallback?.Invoke(); Instance.InitRenderTarget(); Instance.InitDepthStencil(); ImmediateContext. OutputMerger.SetTargets(Instance._depthStencil, Instance._renderTarget); Instance.InitViewport(); MessagePump.Run(Instance, Instance.Loop); onClose?.Invoke(); onClose = null; Instance.DisposeContent(); }
public void TearDown() { testCancellationTokenSource?.Dispose(); MessagePump?.Stop().GetAwaiter().GetResult(); TransportInfrastructure?.Stop().GetAwaiter().GetResult(); Configurer?.Cleanup().GetAwaiter().GetResult(); }
static void Main() { Scene scene = new Scene(); System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); GameTime time = new GameTime(); MessagePump.Run(scene.GraphicsEngine.Form, () => { watch.Reset(); watch.Start(); int frameTime = 1; if (time.LastFrameElapsedTime.TotalMilliseconds < frameTime) { System.Threading.Thread.Sleep((int)(frameTime - time.LastFrameElapsedTime.TotalMilliseconds)); } scene.Update(time); scene.Draw(); watch.Stop(); time.LastFrameElapsedTime = watch.Elapsed; time.TotalGameTime = time.TotalGameTime + watch.Elapsed; }); scene.Dispose(); // TODO ce soir // frustrum culling pour la planète. // backface culling pour le ground. // }
static void Init() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); foreach (KeyValuePair <LibraryFile, string> pair in Libraries.LibraryList) { if (!File.Exists(@".\" + pair.Value)) { continue; } CEnvir.LibraryList[pair.Key] = new MirLibrary(@".\" + pair.Value); } CEnvir.LoadDatabase(); CEnvir.Target = new TargetForm(); DXManager.Create(); DXSoundManager.Create(); DXControl.ActiveScene = new LoginScene(Config.IntroSceneSize); MessagePump.Run(CEnvir.Target, CEnvir.GameLoop); CEnvir.Session?.Save(true); CEnvir.Unload(); DXManager.Unload(); DXSoundManager.Unload(); }
public MainForm() { _stopwatchFrequency = Stopwatch.Frequency; _targetFrameTicks = _stopwatchFrequency / _targetFramesPerSecond; InitializeComponent(); _config = EmulatorConfig.Load(); BuildMainMenu(); SetFormStyles(); _messagePump = new MessagePump(); _audioDevice = new AudioDevice(this.Handle); _soundEffects = LoadSoundEffects(); _renderer = new GdiRenderer(this); _displayBuffer = new DirectBitmap(_screenWidth, _screenHeight); _display = new byte[0x1C00]; _invaders = new SpaceInvaders(PlaySound); _input = new InputState(); InitializeOverlay(); }
public IEnumerable<IMessagePump> CreateAll() { _logger.Debug("Creating request message pumps"); var requestTypes = _requestHandlerTypes.Value.SelectMany(ht => ht.GetGenericInterfacesClosing(typeof (IHandleRequest<,>))) .Select(gi => gi.GetGenericArguments().First()) .OrderBy(t => t.FullName) .Distinct() .ToArray(); foreach (var requestType in requestTypes) { _logger.Debug("Creating message pump for request type {0}", requestType.Name); var queuePath = PathFactory.QueuePathFor(requestType); var messageReceiver = new NimbusQueueMessageReceiver(_queueManager, queuePath, _concurrentHandlerLimit); _garbageMan.Add(messageReceiver); var dispatcher = new RequestMessageDispatcher(_messagingFactory, requestType, _requestHandlerFactory, _clock); _garbageMan.Add(dispatcher); var pump = new MessagePump(messageReceiver, dispatcher, _logger, _clock); _garbageMan.Add(pump); yield return pump; } }
public IEnumerable<IMessagePump> CreateAll() { _logger.Debug("Creating command message pumps"); var commandTypes = _commandHandlerTypes.Value.SelectMany(ht => ht.GetGenericInterfacesClosing(typeof (IHandleCommand<>))) .Select(gi => gi.GetGenericArguments().First()) .OrderBy(t => t.FullName) .Distinct() .ToArray(); foreach (var commandType in commandTypes) { _logger.Debug("Creating message pump for command type {0}", commandType.Name); var queuePath = PathFactory.QueuePathFor(commandType); var messageReceiver = _messagingFactory.GetQueueReceiver(queuePath); var dispatcher = new CommandMessageDispatcher(_commandHandlerFactory, commandType, _clock); _garbageMan.Add(dispatcher); var pump = new MessagePump(messageReceiver, dispatcher, _logger, _clock); _garbageMan.Add(pump); yield return pump; } }
public IEnumerable<IMessagePump> CreateAll() { _logger.Debug("Creating competing event message pumps"); var eventTypes = _competingEventHandlerTypes.Value.SelectMany(ht => ht.GetGenericInterfacesClosing(typeof (IHandleCompetingEvent<>))) .Select(gi => gi.GetGenericArguments().Single()) .OrderBy(t => t.FullName) .Distinct() .ToArray(); foreach (var eventType in eventTypes) { _logger.Debug("Registering Message Pump for Competing Event type {0}", eventType.Name); var topicPath = PathFactory.TopicPathFor(eventType); var subscriptionName = String.Format("{0}", _applicationName); var receiver = _messagingFactory.GetTopicReceiver(topicPath, subscriptionName); var dispatcher = new CompetingEventMessageDispatcher(_competingEventHandlerFactory, eventType, _clock); _garbageMan.Add(dispatcher); var pump = new MessagePump(receiver, dispatcher, _logger, _clock); _garbageMan.Add(pump); yield return pump; } }
private double OpenFiles(IEnumerable <string> filePaths, bool logTimming = false) { var count = filePaths.Count(); var i = 0; var time = Helper.GetExecutionTime(() => { foreach (var filePath in filePaths) { i++; var fileTime = Helper.GetExecutionTime(() => { var id = OpenTile(filePath); mapIds.Add(id); Zoom(); MessagePump.DoEvents(); }); if (logTimming) { Helper.Log(">>> OPEN FILE {1}/{2} {3:0.00} {0}", filePath, i, count, fileTime); } else { Helper.Trace(">>> OPEN FILE {1}/{2} {3:0.00} {0}", filePath, i, count, fileTime); } } }); return(time); }
private double CloseFiles(bool logTimming = false) { var count = mapIds.Count(); var i = 0; var time = Helper.GetExecutionTime(() => { foreach (var id in mapIds.ToArray()) { i++; var fileTime = Helper.GetExecutionTime(() => { CloseTile(id); mapIds.Remove(id); Zoom(); MessagePump.DoEvents(); }); if (logTimming) { Helper.Log(">>> CLOSE FILE {0}/{1} {2:0.00}", i, count, fileTime); } else { Helper.Trace(">>> CLOSE FILE {0}/{1} {2:0.00}", i, count, fileTime); } } }); return(time); }
static void Main() { Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); MessagePump.Run(new Form1()); }
public IEnumerable <IMessagePump> CreateAll() { var openGenericHandlerType = typeof(IHandleCommand <>); var handlerTypes = _typeProvider.CommandHandlerTypes.ToArray(); // Create a single connection to each command queue determined by routing var allMessageTypesHandledByThisEndpoint = _handlerMapper.GetMessageTypesHandledBy(openGenericHandlerType, handlerTypes); var bindings = allMessageTypesHandledByThisEndpoint .Select(m => new { MessageType = m, QueuePath = _router.Route(m, QueueOrTopic.Queue) }) .GroupBy(b => b.QueuePath) .Select(g => new { QueuePath = g.Key, HandlerTypes = g.SelectMany(x => _handlerMapper.GetHandlerTypesFor(openGenericHandlerType, x.MessageType)) }); // Each binding to a queue can handle one or more command types depending on the routes that are defined foreach (var binding in bindings) { var messageTypes = _handlerMapper.GetMessageTypesHandledBy(openGenericHandlerType, binding.HandlerTypes).ToArray(); _logger.Debug("Creating message pump for command queue '{0}' handling {1}", binding.QueuePath, messageTypes.ToTypeNameSummary(selector: t => t.Name)); var messageReceiver = _messagingFactory.GetQueueReceiver(binding.QueuePath); var handlerMap = _handlerMapper.GetHandlerMapFor(openGenericHandlerType, messageTypes); var pump = new MessagePump(_clock, _dispatchContextManager, _logger, _messageDispatcherFactory.Create(openGenericHandlerType, handlerMap), messageReceiver, _taskFactory); _garbageMan.Add(pump); yield return(pump); } }
public async Task Should_stop_pumping_messages_after_first_unsuccessful_receive() { var successfulReceives = 46; var queueSize = 1000; var parser = new QueueAddressTranslator("nservicebus", "dbo", null, null); var inputQueue = new FakeTableBasedQueue(parser.Parse("input").QualifiedTableName, queueSize, successfulReceives); var pump = new MessagePump( m => new ProcessWithNoTransaction(sqlConnectionFactory), qa => qa == "input" ? (TableBasedQueue)inputQueue : new TableBasedQueue(parser.Parse(qa).QualifiedTableName, qa), new QueuePurger(sqlConnectionFactory), new ExpiredMessagesPurger(_ => sqlConnectionFactory.OpenNewConnection(), TimeSpan.MaxValue, 0), new QueuePeeker(sqlConnectionFactory, new QueuePeekerOptions()), new SchemaInspector(_ => sqlConnectionFactory.OpenNewConnection()), TimeSpan.MaxValue); await pump.Init( _ => Task.FromResult(0), _ => Task.FromResult(ErrorHandleResult.Handled), new CriticalError(_ => Task.FromResult(0)), new PushSettings("input", "error", false, TransportTransactionMode.None)); pump.Start(new PushRuntimeSettings(1)); await WaitUntil(() => inputQueue.NumberOfPeeks > 1); await pump.Stop(); Assert.That(inputQueue.NumberOfReceives, Is.AtMost(successfulReceives + 2), "Pump should stop receives after first unsuccessful attempt."); }
protected async Task StartPump(Func <MessageContext, Task> onMessage, Func <ErrorContext, Task <ErrorHandleResult> > onError, TransportTransactionMode transactionMode, Action <string, Exception> onCriticalError = null) { InputQueueName = GetTestName() + transactionMode; ErrorQueueName = $"{InputQueueName}.error"; transportSettings.Set("NServiceBus.Routing.EndpointName", InputQueueName); var queueBindings = new QueueBindings(); queueBindings.BindReceiving(InputQueueName); queueBindings.BindSending(ErrorQueueName); transportSettings.Set(ErrorQueueSettings.SettingsKey, ErrorQueueName); transportSettings.Set <QueueBindings>(queueBindings); transportSettings.Set <EndpointInstances>(new EndpointInstances()); Configurer = CreateConfigurer(); var configuration = Configurer.Configure(transportSettings, transactionMode); TransportInfrastructure = configuration.TransportInfrastructure; IgnoreUnsupportedTransactionModes(transactionMode); IgnoreUnsupportedDeliveryConstraints(); ReceiveInfrastructure = TransportInfrastructure.ConfigureReceiveInfrastructure(); SendInfrastructure = TransportInfrastructure.ConfigureSendInfrastructure(); lazyDispatcher = new Lazy <IDispatchMessages>(() => SendInfrastructure.DispatcherFactory()); MessagePump = ReceiveInfrastructure.MessagePumpFactory(); var queueCreator = ReceiveInfrastructure.QueueCreatorFactory(); await queueCreator.CreateQueueIfNecessary(queueBindings, WindowsIdentity.GetCurrent().Name); var pushSettings = new PushSettings(InputQueueName, ErrorQueueName, configuration.PurgeInputQueueOnStartup, transactionMode); await MessagePump.Init( context => { if (context.Headers.ContainsKey(TestIdHeaderName) && context.Headers[TestIdHeaderName] == testId) { return(onMessage(context)); } return(Task.FromResult(0)); }, context => { if (context.Message.Headers.ContainsKey(TestIdHeaderName) && context.Message.Headers[TestIdHeaderName] == testId) { return(onError(context)); } return(Task.FromResult(ErrorHandleResult.Handled)); }, new FakeCriticalError(onCriticalError), pushSettings); MessagePump.Start(configuration.PushRuntimeSettings); }
/// <summary> /// Runs this game mode client. /// </summary> /// <returns>true if shut down by the game mode, false otherwise.</returns> /// <exception cref="Exception">Thrown if a game mode is already running.</exception> public bool Run() { if (InternalStorage.RunningClient != null) { throw new Exception("A game mode is already running!"); } InternalStorage.RunningClient = this; // Prepare the syncronization context var queue = new SemaphoreMessageQueue(); _syncronizationContext = new SampSharpSyncronizationContext(queue); _messagePump = new MessagePump(queue); SynchronizationContext.SetSynchronizationContext(_syncronizationContext); // Initialize the game mode and start the main routine Initialize(); // Pump new tasks _messagePump.Pump(e => OnUnhandledException(new UnhandledExceptionEventArgs(e))); // Clean up InternalStorage.RunningClient = null; CommunicationClient.Disconnect(); return(_shuttingDown); }
static void Main(string[] args) { // Setup var form = SlimDXHelper.InitD3D(out _device, out _swapChain, out _renderView); var temp = form.ClientRectangle; _finalRender = new FSQ(_device, _renderView, "SimpleFSQ.fx"); /*_simulation = * new HybridFluidSim( * _finalRender, * _device);*/ _simulation = new SemiGridSPHSimulation(_device, _finalRender.UAV); //_simulation = new MovingGridFluid.MovingGridFluid(_device, _finalRender.UAV); // Main loop MessagePump.Run(form, SimMain); // Tear down _finalRender.Dispose(); _swapChain.Dispose(); _renderView.Dispose(); _simulation.Dispose(); _device.Dispose(); }
public IEnumerable<IMessagePump> CreateAll() { _logger.Debug("Creating multicast event message pumps"); var eventTypes = _multicastEventHandlerTypes.Value .SelectMany(ht => ht.GetGenericInterfacesClosing(typeof (IHandleMulticastEvent<>))) .Select(gi => gi.GetGenericArguments().Single()) .OrderBy(t => t.FullName) .Distinct() .ToArray(); foreach (var eventType in eventTypes) { _logger.Debug("Creating message pump for multicast event type {0}", eventType.Name); var topicPath = PathFactory.TopicPathFor(eventType); var subscriptionName = String.Format("{0}.{1}", _applicationName, _instanceName); var receiver = new NimbusSubscriptionMessageReceiver(_queueManager, topicPath, subscriptionName, _concurrentHandlerLimit); _garbageMan.Add(receiver); var dispatcher = new MulticastEventMessageDispatcher(_multicastEventHandlerFactory, eventType, _clock); _garbageMan.Add(dispatcher); var pump = new MessagePump(receiver, dispatcher, _logger, _clock); _garbageMan.Add(pump); yield return pump; } }
public void Run() { this.Height = this.Width = 800; InitializeDevice(); MessagePump.Run(this, Draw); DisposeDevice(); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); MainController c = new MainController(); MessagePump.Run(c, c.PostWindowsLoop); }
public void NetStateConstructorTest() { ClientSocketManager clientSocket = null; // TODO: 初始化为适当的值 MessagePump messagePump = null; // TODO: 初始化为适当的值 NetState target = new NetState(clientSocket, messagePump); Assert.Inconclusive("TODO: 实现用来验证目标的代码"); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var form = new RenderForm(); MessagePump.Run(form, form.RenderFrame); }
public void ConnectersTest() { MessagePump target = new MessagePump(); // TODO: 初始化为适当的值 Connecter[] actual; actual = target.Connecters; Assert.Inconclusive("验证此测试方法的正确性。"); }
public void AddMessagePumpTest() { BaseWorld target = new BaseWorld(); // TODO: 初始化为适当的值 MessagePump messagePump = null; // TODO: 初始化为适当的值 target.AddMessagePump(messagePump); Assert.Inconclusive("无法验证不返回值的方法。"); }
public void AddConnecterTest() { MessagePump target = new MessagePump(); // TODO: 初始化为适当的值 Connecter connecter = null; // TODO: 初始化为适当的值 target.AddConnecter(connecter); Assert.Inconclusive("无法验证不返回值的方法。"); }
public void AddListenerTest() { MessagePump target = new MessagePump(); // TODO: 初始化为适当的值 Listener listener = null; // TODO: 初始化为适当的值 target.AddListener(listener); Assert.Inconclusive("无法验证不返回值的方法。"); }
public void OnNetStateInitTest() { MessagePump target = new MessagePump(); // TODO: 初始化为适当的值 NetState newNetState = null; // TODO: 初始化为适当的值 target.OnNetStateInit(newNetState); Assert.Inconclusive("无法验证不返回值的方法。"); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 renderForm = new Form1(); MessagePump.Run(renderForm, renderForm.engine.MainLoop); }
public void DisposeTest1() { ClientSocketManager clientSocket = null; // TODO: 初始化为适当的值 MessagePump messagePump = null; // TODO: 初始化为适当的值 NetState target = new NetState(clientSocket, messagePump); // TODO: 初始化为适当的值 target.Dispose(); Assert.Inconclusive("无法验证不返回值的方法。"); }
public void Run(Action firstFrame = null) { try { _firstFrame = firstFrame; MessagePump.Run(Form, OnRender); } catch (InvalidOperationException e) { AcToolsLogging.Write(e); } }
public IMessagePump Create() { var receiver = new NimbusQueueMessageReceiver(_queueManager, _replyQueueName, _concurrentHandlerLimit, _logger); _garbageMan.Add(receiver); var pump = new MessagePump(_clock, _dispatchContextManager, _logger, _messageDispatcher, receiver, _taskFactory); _garbageMan.Add(pump); return pump; }
public IMessagePump Create() { var receiver = new NimbusQueueMessageReceiver(_queueManager, _replyQueueName, _concurrentHandlerLimit); _garbageMan.Add(receiver); var pump = new MessagePump(receiver, _dispatcher, _logger, _clock); _garbageMan.Add(pump); return pump; }
public void ShouldThrowIfConfiguredToReceiveFromRemoteQueue() { var messagePump = new MessagePump(mode => null); var pushSettings = new PushSettings("queue@remote", "error", false, TransportTransactionMode.None); var exception = Assert.Throws<Exception>(() => { messagePump.Init(context => null, context => null, null, pushSettings); }); Assert.That(exception.Message, Does.Contain($"MSMQ Dequeuing can only run against the local machine. Invalid inputQueue name '{pushSettings.InputQueue}'.")); }
public IEnumerable<IMessagePump> CreateAll() { var openGenericHandlerType = typeof (IHandleMulticastEvent<>); var handlerTypes = _typeProvider.MulticastEventHandlerTypes.ToArray(); // Events are routed to Topics and we'll create a subscription per instance of the logical endpoint to enable multicast behaviour var allMessageTypesHandledByThisEndpoint = _handlerMapper.GetMessageTypesHandledBy(openGenericHandlerType, handlerTypes); var bindings = allMessageTypesHandledByThisEndpoint .Select(m => new {MessageType = m, TopicPath = _router.Route(m, QueueOrTopic.Topic)}) .GroupBy(b => b.TopicPath) .Select(g => new { TopicPath = g.Key, MessageTypes = g.Select(x => x.MessageType), HandlerTypes = g.SelectMany(x => _handlerMapper.GetHandlerTypesFor(openGenericHandlerType, x.MessageType)) }) .ToArray(); if (bindings.Any(b => b.MessageTypes.Count() > 1)) throw new NotSupportedException("Routing multiple message types through a single Topic is not supported."); foreach (var binding in bindings) { foreach (var handlerType in binding.HandlerTypes) { var messageType = binding.MessageTypes.Single(); var subscriptionName = PathFactory.SubscriptionNameFor(_applicationName, _instanceName, handlerType); _logger.Debug("Creating message pump for multicast event subscription '{0}/{1}' handling {2}", binding.TopicPath, subscriptionName, messageType); var messageReceiver = _messagingFactory.GetTopicReceiver(binding.TopicPath, subscriptionName); var handlerMap = new Dictionary<Type, Type[]> {{messageType, new[] {handlerType}}}; var pump = new MessagePump(_clock, _dispatchContextManager, _logger, _messageDispatcherFactory.Create(openGenericHandlerType, handlerMap), messageReceiver); _garbageMan.Add(pump); yield return pump; } } }
private void initialize() { string plugin_base; string[] plugins; try{ this._base_port = this._configuration.get_asInt("ListenPort"); } catch(Exception e){ this._base_port = -1; } this._connections = new ArrayList(); this._plugins = new PluginManager(this); try { plugin_base = this._configuration.get_value("Plugins"); plugins = plugin_base.Split('|'); foreach(string plugin in plugins) { try { this._plugins.register(plugin); } catch(Exception e) { Logger.log("Error detected while loading plugin ("+plugin+")", Logger.Verbosity.moderate); Logger.log("'- "+e.Message, Logger.Verbosity.moderate); } } } catch(ItemNotFound e) { Logger.log("No plugins specified to load in configuration file.", Logger.Verbosity.moderate); } catch(Exception e) { Logger.log("Failed to load plugins. No plugins loaded.", Logger.Verbosity.moderate); } this.LinkPlugins(); this._base_listener = this._base_port == -1 ? new Listener(this._connections) : new Listener(this._base_port, this._connections); this._message_pump = new MessagePump(this._plugins, this._connections); this._message_pump.deleteConnection = this.DeleteConnection; this._base_listener.connection_announcement += new NewConnection(this._message_pump.RegisterConnection); }