Exemple #1
0
 void ActionDispatcher_OnProccesingEnd()
 {
     Array.ForEach(pipes, p => p.ActionToken.ClearSingleRunValues());
     resourceManager.FreeResources();
     lock (evaluationLock)
         state = DispatcherState.Finished;
 }
Exemple #2
0
 public bool Dispatch(int ThreadCount, int ExecuteInt)
 {
     if (State != DispatcherState.IDLE)
     {
         return(false);
     }
     State           = DispatcherState.INIT;
     Living          = ThreadCount;
     ExecuteInterval = ExecuteInt;
     limitAvailale   = Limit;
     WorkingThread   = new Thread[ThreadCount];
     State           = DispatcherState.BUSY;
     for (int i = 0; i < WorkingThread.Length; i++)
     {
         WorkerArgs Args = new WorkerArgs()
         {
             ThreadIndex = i
         };
         WorkingThread[i] = new Thread(new ParameterizedThreadStart(ThreadWork))
         {
             IsBackground = true
         };
         WorkingThread[i].Start(Args);
     }
     return(true);
 }
Exemple #3
0
 public bool Halt()
 {
     if (State != DispatcherState.BUSY)
     {
         return(false);
     }
     State = DispatcherState.HALTING;
     BackgroundThread(() =>
     {
         for (int i = 0; i < WorkingThread.Length; i++)
         {
             try
             {
                 WorkingThread[i].Abort();
             }
             catch
             {
             }
         }
         State = DispatcherState.IDLE;
         if (DispatchFinished != null)
         {
             DispatchFinished(this);
         }
     });
     return(true);
 }
Exemple #4
0
 public void Stop()
 {
     lock (TaskLock)
     {
         State = DispatcherState.Closing;
     }
 }
Exemple #5
0
 public Dispatcher()
 {
     LivingLock    = new object();
     Tag           = null;
     State         = DispatcherState.IDLE;
     DispatchQueue = Queue.Synchronized(new Queue());
 }
Exemple #6
0
 public bool Halt()
 {
     if (State != DispatcherState.BUSY)
     {
         return(false);
     }
     State = DispatcherState.HALTING;
     new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
     {
         for (int i = 0; i < WorkingThread.Length; i++)
         {
             try
             {
                 WorkingThread[i].Abort();
             }
             catch
             {
             }
         }
         State = DispatcherState.IDLE;
         if (DispatchFinished != null)
         {
             DispatchFinished(this);
         }
     }))
     {
         IsBackground = true
     }.Start();
     return(true);
 }
Exemple #7
0
 public void Start()
 {
     State               = DispatcherState.Running;
     Signaler            = new AutoResetEvent(false);
     Thread              = new Thread(DispatcherThread);
     Thread.IsBackground = true;
     Thread.Start();
 }
Exemple #8
0
 /// <summary>
 ///
 /// </summary>
 public void Halt()
 {
     if (state != DispatcherState.BUSY)
     {
         return;
     }
     state = DispatcherState.HALTING;
 }
 public void Save(DispatcherState state)
 {
     _db.RetryOnTransientError(db =>
     {
         db.Connection.Update <ServerStateItem>()
         .Set(d => d.Data, state.Serialize())
         .Execute();
     });
 }
Exemple #10
0
        private void Start()
        {
            _controlTask = Task.Factory.StartNew(() =>
            {
                if (State == DispatcherState.DS_AWAITING || State == DispatcherState.DS_STOPPED)
                {
                    _logger.Info("Dispatcher: Dispatcher starting");
                    State = DispatcherState.DS_RUNNING;

                    var consumers = Consumers.ToArray();
                    consumers.Each((consumer) => consumer.Open());
                    consumers.Each(consumer => _tasks.TryAdd(consumer.JobId, consumer.Job));

                    _logger.InfoFormat("Dispatcher: Dispatcher starting {0} performers", _tasks.Count);

                    while (!_tasks.IsEmpty)
                    {
                        try
                        {
                            var runningTasks     = _tasks.Values.ToArray();
                            var index            = Task.WaitAny(runningTasks);
                            var stoppingConsumer = runningTasks[index];
                            _logger.DebugFormat("Dispatcher: Performer stopped with state {0}", stoppingConsumer.Status);

                            var consumer = Consumers.SingleOrDefault(c => c.JobId == stoppingConsumer.Id);
                            if (consumer != null)
                            {
                                _logger.DebugFormat("Dispatcher: Removing a consumer with connection name {0}", consumer.Name);
                                consumer.Dispose();

                                _consumers.TryRemove(consumer.Name, out consumer);
                            }

                            //_tasks[index].Dispose();
                            //_tasks.RemoveAt(index);
                            //_tasks.TryTake(out )
                            Task removedTask;
                            _tasks.TryRemove(stoppingConsumer.Id, out removedTask);
                        }
                        catch (AggregateException ae)
                        {
                            ae.Handle(
                                (ex) =>
                            {
                                _logger.ErrorFormat("Dispatcher: Error on consumer; consumer shut down");
                                return(true);
                            });
                        }
                    }

                    State = DispatcherState.DS_STOPPED;
                    _logger.Info("Dispatcher: Dispatcher stopped");
                }
            },
                                                 TaskCreationOptions.LongRunning);
        }
Exemple #11
0
        public void Shutdown()
        {
            lock (TaskLock)
            {
                State = DispatcherState.Terminated;
                Flush();
            }

            Signaler.Set();
        }
        public void Stop()
        {
            lock (_lock)
            {
                if (_state != DispatcherState.Running)
                {
                    return;
                }

                _state = DispatcherState.Closing;
            }
        }
Exemple #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Dispatcher"/> class.
        /// </summary>
        /// <param name="commandProcessor">The command processor.</param>
        /// <param name="messageMapperRegistry">The message mapper registry.</param>
        /// <param name="connections">The connections.</param>
        /// <param name="logger">The logger.</param>
        public Dispatcher(IAmACommandProcessor commandProcessor, IAmAMessageMapperRegistry messageMapperRegistry, IEnumerable <Connection> connections, ILog logger)
        {
            this.commandProcessor      = commandProcessor;
            this.messageMapperRegistry = messageMapperRegistry;
            this.Connections           = connections;
            this.logger = logger;
            State       = DispatcherState.DS_NOTREADY;

            Consumers = new SynchronizedCollection <Consumer>();

            State = DispatcherState.DS_AWAITING;
        }
        public void Start()
        {
            lock (_lock)
            {
                if (_state == DispatcherState.Running)
                    return;

                _state = DispatcherState.Running;
                _thread = new Thread(Run) { IsBackground = false };
                _thread.Start();
            }
        }
Exemple #15
0
        public Dispatcher(IAmACommandProcessor commandProcessor, IAmAMessageMapperRegistry messageMapperRegistry, IEnumerable<Connection> connections, ILog logger)
        {
            this.commandProcessor = commandProcessor;
            this.messageMapperRegistry = messageMapperRegistry;
            this.logger = logger;
            State = DispatcherState.DS_NOTREADY;

            Consumers = new SynchronizedCollection<Consumer>();
            CreateConsumers(connections).Each(consumer => Consumers.Add(consumer));
            
            State = DispatcherState.DS_AWAITING;
            logger.Debug(m => m("Dispatcher is ready to recieve"));
        }
        public void Shutdown()
        {
            lock (_lock)
            {
                if (_state == DispatcherState.Terminated)
                    throw new InvalidOperationException("The dispatcher is already terminated.");

                _state = DispatcherState.Terminated;
                _queue.Clear();

                Monitor.Pulse(_lock);
            }
        }
Exemple #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Dispatcher"/> class.
        /// </summary>
        /// <param name="commandProcessor">The command processor.</param>
        /// <param name="messageMapperRegistry">The message mapper registry.</param>
        /// <param name="connections">The connections.</param>
        /// <param name="logger">The logger.</param>
        public Dispatcher(IAmACommandProcessor commandProcessor, IAmAMessageMapperRegistry messageMapperRegistry, IEnumerable <Connection> connections, ILog logger)
        {
            this.commandProcessor      = commandProcessor;
            this.messageMapperRegistry = messageMapperRegistry;
            this.logger = logger;
            State       = DispatcherState.DS_NOTREADY;

            Consumers = new SynchronizedCollection <Consumer>();
            CreateConsumers(connections).Each(consumer => Consumers.Add(consumer));

            State = DispatcherState.DS_AWAITING;
            logger.Debug(m => m("Dispatcher is ready to recieve"));
        }
        public void Shutdown()
        {
            lock (_lock)
            {
                if (_state == DispatcherState.Terminated)
                    return;

                _state = DispatcherState.Terminated;
                _queue.Clear();

                Monitor.Pulse(_lock);
            }
        }
Exemple #19
0
        private void Start()
        {
            controlTask = Task.Factory.StartNew(
                () =>
            {
                if (State == DispatcherState.DS_AWAITING || State == DispatcherState.DS_STOPPED)
                {
                    State = DispatcherState.DS_RUNNING;
                    logger.Info("Dispatcher: Dispatcher starting");

                    Consumers.Each((consumer) => consumer.Open());

                    Consumers.Select(consumer => consumer.Job).Each(job => tasks.Add(job));

                    logger.InfoFormat("Dispatcher: Dispatcher starting {0} performers", tasks.Count);

                    while (tasks.Any())
                    {
                        try
                        {
                            var index = Task.WaitAny(tasks.ToArray());
                            logger.DebugFormat("Dispatcher: Performer stopped with state {0}", tasks[index].Status);

                            var consumer = Consumers.SingleOrDefault(c => c.JobId == tasks[index].Id);
                            if (consumer != null)
                            {
                                logger.DebugFormat("Dispatcher: Removing a consumer with connection name {0}", consumer.Name);
                                consumer.Dispose();
                                Consumers.Remove(consumer);
                            }

                            tasks[index].Dispose();
                            tasks.RemoveAt(index);
                        }
                        catch (AggregateException ae)
                        {
                            ae.Handle(
                                (ex) =>
                            {
                                logger.ErrorFormat("Dispatcher: Error on consumer; consumer shut down");
                                return(true);
                            });
                        }
                    }

                    State = DispatcherState.DS_STOPPED;
                    logger.Info("Dispatcher: Dispatcher stopped");
                }
            },
                TaskCreationOptions.LongRunning);
        }
        public void Shutdown()
        {
            lock (_lock)
            {
                if (_state == DispatcherState.Terminated)
                {
                    return;
                }

                _state = DispatcherState.Terminated;
                _queue.Clear();

                Monitor.Pulse(_lock);
            }
        }
Exemple #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Dispatcher"/> class.
        /// </summary>
        /// <param name="commandProcessor">The command processor.</param>
        /// <param name="messageMapperRegistry">The message mapper registry.</param>
        /// <param name="connections">The connections.</param>
        public Dispatcher(
            IAmACommandProcessor commandProcessor,
            IAmAMessageMapperRegistry messageMapperRegistry,
            IEnumerable <Subscription> connections)
        {
            CommandProcessor       = commandProcessor;
            Connections            = connections;
            _messageMapperRegistry = messageMapperRegistry;

            State = DispatcherState.DS_NOTREADY;

            _tasks     = new ConcurrentDictionary <int, Task>();
            _consumers = new ConcurrentDictionary <string, IAmAConsumer>();

            State = DispatcherState.DS_AWAITING;
        }
Exemple #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Dispatcher"/> class.
        /// Use this if you need to inject a logger, for example for testing
        /// </summary>
        /// <param name="commandProcessor">The command processor.</param>
        /// <param name="messageMapperRegistry">The message mapper registry.</param>
        /// <param name="connections">The connections.</param>
        /// <param name="logger">The logger.</param>
        public Dispatcher(
            IAmACommandProcessor commandProcessor,
            IAmAMessageMapperRegistry messageMapperRegistry,
            IEnumerable <Connection> connections,
            ILog logger)
        {
            CommandProcessor       = commandProcessor;
            _messageMapperRegistry = messageMapperRegistry;
            this.Connections       = connections;
            _logger = logger;
            State   = DispatcherState.DS_NOTREADY;

            _consumers = new ConcurrentDictionary <string, IAmAConsumer>();

            State = DispatcherState.DS_AWAITING;
        }
Exemple #23
0
        public ActionDispatcher(IEnumerable <IActionPipe> actionPipes, int numberOfThreadPoolThreads = 8)
        {
            pipes           = actionPipes.ToArray();
            resourceManager = new ResourceManager();

            cancellationTokenSource = new CancellationTokenSource();
            tasks = new Dictionary <IActionPipe, Task>(pipes.Length);

            pool        = new DedicatedThreadPool(new DedicatedThreadPoolSettings(numberOfThreadPoolThreads));
            Scheduler   = new DedicatedThreadPoolTaskScheduler(pool);
            TaskFactory = new TaskFactory(cancellationTokenSource.Token, TaskCreationOptions.None, TaskContinuationOptions.None, Scheduler);

            SetUpProcessingDefaultEvents();

            state = DispatcherState.NotStarted;
        }
        public void Start()
        {
            lock (_lock)
            {
                if (_state == DispatcherState.Running)
                {
                    return;
                }

                _state  = DispatcherState.Running;
                _thread = new Thread(Run)
                {
                    IsBackground = false
                };
                _thread.Start();
            }
        }
Exemple #25
0
        public void Restart()
        {
            if (!IsFinished)
            {
                throw new InvalidOperationException();
            }

            lock (evaluationLock)
            {
                state = DispatcherState.Unspecified;
                foreach (var pipe in pipes)
                {
                    pipe.Restart();
                }
                state = DispatcherState.NotStarted;
            }
        }
Exemple #26
0
        /// <summary>
        /// Handle a socket accept
        /// </summary>
        private void AcceptSocket(IAsyncResult result)
        {
            State = DispatcherState.AcceptingSocket;
            Socket sock = m_listener.EndAcceptSocket(result);

            //Queue the next accept
            BeginAcceptingSockets();

            //Fire the event handler for sockets
            if (SocketConnected != null)
            {
                SocketConnected(sock);
            }
            else
            {
                //boot the user if nobody is listening
                sock.Disconnect(false);
            }
        }
        public async Task InvokeShutdownAsync()
        {
            await _shutdownSemaphore.WaitAsync();

            try
            {
                if (State != DispatcherState.Running)
                {
                    throw new DispatcherException($"Cannot shutdown dispatcher in current state {State}.");
                }

                State = DispatcherState.ShuttingDown;
                _newWorkSemaphore.Release();
            }
            finally
            {
                _shutdownSemaphore.Release();
            }

            await _shutdownTaskCompletionSource.Task;
        }
Exemple #28
0
        public void Recieve()
        {
            controlTask = Task.Factory.StartNew(() =>
            {
                if (State == DispatcherState.DS_AWAITING || State == DispatcherState.DS_STOPPED)
                {
                    State = DispatcherState.DS_RUNNING;
                    logger.Debug(m => m("Dispatcher: Dispatcher starting"));

                    Consumers.Each((consumer) => consumer.Open());

                    Consumers.Select(consumer => consumer.Job).Each(job => tasks.Add(job));

                    logger.Debug(m => m("Dispatcher: Dispatcher starting {0} performers", tasks.Count));

                    while (tasks.Any())
                    {
                        try
                        {
                            var index = Task.WaitAny(tasks.ToArray());
                            //TODO: This doesn't really identify the connection that we closed - which is what we want diagnostically
                            logger.Debug(m => m("Dispatcher: Performer stopped with state {0}", tasks[index].Status));
                            tasks.RemoveAt(index);
                        }
                        catch (AggregateException ae)
                        {
                            ae.Handle((ex) =>
                                {
                                    logger.Error(m => m("Dispatcher: Error on consumer; consumer shut down"));
                                    return true;
                                });
                        }
                    }

                    State = DispatcherState.DS_STOPPED;
                    logger.Debug(m => m("Dispatcher: Dispatcher stopped"));
                }
            },
            TaskCreationOptions.LongRunning);
        }
Exemple #29
0
        /// <summary>
        /// Begins listening for messages on channels, and dispatching them to request handlers.
        /// </summary>
        public void Receive()
        {
            controlTask = Task.Factory.StartNew(() =>
            {
                if (State == DispatcherState.DS_AWAITING || State == DispatcherState.DS_STOPPED)
                {
                    State = DispatcherState.DS_RUNNING;
                    logger.Debug(m => m("Dispatcher: Dispatcher starting"));

                    Consumers.Each((consumer) => consumer.Open());

                    Consumers.Select(consumer => consumer.Job).Each(job => tasks.Add(job));

                    logger.Debug(m => m("Dispatcher: Dispatcher starting {0} performers", tasks.Count));

                    while (tasks.Any())
                    {
                        try
                        {
                            var index = Task.WaitAny(tasks.ToArray());
                            //TODO: This doesn't really identify the connection that we closed - which is what we want diagnostically
                            logger.Debug(m => m("Dispatcher: Performer stopped with state {0}", tasks[index].Status));
                            tasks.RemoveAt(index);
                        }
                        catch (AggregateException ae)
                        {
                            ae.Handle((ex) =>
                            {
                                logger.Error(m => m("Dispatcher: Error on consumer; consumer shut down"));
                                return(true);
                            });
                        }
                    }

                    State = DispatcherState.DS_STOPPED;
                    logger.Debug(m => m("Dispatcher: Dispatcher stopped"));
                }
            },
                                                TaskCreationOptions.LongRunning);
        }
Exemple #30
0
        /// <summary>
        /// 开启线程池调度
        /// </summary>
        /// <param name="threadCount"></param>
        /// <param name="execInterv"></param>
        public void Start(int threadCount)
        {
            if (state == DispatcherState.BUSY)
            {
                return;
            }
            ThreadCount  = threadCount;
            exitedThread = 0;
            state        = DispatcherState.BUSY;
            threads      = new Thread[threadCount];
            for (int i = 0; i < threadCount; i++)
            {
                var thread = new Thread(threadWork);
                thread.IsBackground = true;
                thread.Start();
                threads[i] = threads[i];
            }

            // 监视线程, 负责触发事件
            var daemon = new Thread(() =>
            {
                while (true)
                {
                    // 运行线程已经全部退出
                    if (exitedThread == ThreadCount)
                    {
                        DispatchFinished?.Invoke(this);
                        return;
                    }
                    Thread.Sleep(100);
                }
            })
            {
                IsBackground = true
            };

            daemon.Start();
        }
Exemple #31
0
        protected void DispatcherThread()
        {
            //OutputMessagePool* outputPool = OutputMessagePool::getInstance();
            Task task;

            while (State == DispatcherState.Running)
            {
                if (TaskList.Count == 0)
                {
                    Signaler.WaitOne();
                }

                if (TaskList.Count == 0 || State != DispatcherState.Running)
                {
                    Thread.Sleep(1);
                    continue;
                }

                lock (TaskLock)
                {
                    task = TaskList[0];
                    TaskList.RemoveAt(0);
                }

                if (!task.IsExpired())
                {
                    //outputPool->startExecutionFrame();
                    task.Action.Invoke();
                    OutputMessagePool.Flush();
                    //outputPool->sendAll();

                    //g_game.clearSpectatorCache();
                }
            }

            State = DispatcherState.Terminated;
        }
Exemple #32
0
 void ActionDispatcher_OnProcessingBegin()
 {
     resourceManager.AllocateResources();
     lock (evaluationLock)
         state = DispatcherState.Processing;
 }
Exemple #33
0
        private void Start()
        {
            _controlTask = Task.Factory.StartNew(() =>
            {
                if (State == DispatcherState.DS_AWAITING || State == DispatcherState.DS_STOPPED)
                {
                    s_logger.LogInformation("Dispatcher: Dispatcher starting");
                    State = DispatcherState.DS_RUNNING;

                    var consumers = Consumers.ToArray();
                    consumers.Each(consumer => consumer.Open());
                    consumers.Each(consumer => _tasks.TryAdd(consumer.JobId, consumer.Job));

                    s_logger.LogInformation("Dispatcher: Dispatcher starting {Consumers} performers", _tasks.Count);

                    while (_tasks.Any())
                    {
                        try
                        {
                            var runningTasks     = _tasks.Values.ToArray();
                            var index            = Task.WaitAny(runningTasks);
                            var stoppingConsumer = runningTasks[index];
                            s_logger.LogDebug("Dispatcher: Performer stopped with state {Status}", stoppingConsumer.Status);

                            var consumer = Consumers.SingleOrDefault(c => c.JobId == stoppingConsumer.Id);
                            if (consumer != null)
                            {
                                s_logger.LogDebug("Dispatcher: Removing a consumer with subscription name {ChannelName}", consumer.Name);

                                if (_consumers.TryRemove(consumer.Name, out consumer))
                                {
                                    consumer.Dispose();
                                }
                            }

                            if (_tasks.TryRemove(stoppingConsumer.Id, out Task removedTask))
                            {
                                removedTask.Dispose();
                            }

                            stoppingConsumer.Dispose();
                        }
                        catch (AggregateException ae)
                        {
                            ae.Handle(ex =>
                            {
                                s_logger.LogError(ex, "Dispatcher: Error on consumer; consumer shut down");
                                return(true);
                            });
                        }
                    }

                    State = DispatcherState.DS_STOPPED;
                    s_logger.LogInformation("Dispatcher: Dispatcher stopped");
                }
            },
                                                 TaskCreationOptions.LongRunning);

            while (State != DispatcherState.DS_RUNNING)
            {
                Task.Delay(100).Wait();
            }
        }
Exemple #34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Dispatcher"/> class.
        /// </summary>
        /// <param name="commandProcessor">The command processor.</param>
        /// <param name="messageMapperRegistry">The message mapper registry.</param>
        /// <param name="connections">The connections.</param>
        public Dispatcher(
            IAmACommandProcessor commandProcessor, 
            IAmAMessageMapperRegistry messageMapperRegistry,
            IEnumerable<Connection> connections)
        {
            CommandProcessor = commandProcessor;
            Connections = connections;
            _messageMapperRegistry = messageMapperRegistry;

            State = DispatcherState.DS_NOTREADY;

            _tasks = new ConcurrentDictionary<int, Task>();
            _consumers = new ConcurrentDictionary<string, IAmAConsumer>();

            State = DispatcherState.DS_AWAITING;
        }
        public void Run()
        {
            State = DispatcherState.Running;

            while (true)
            {
                // Wait for new work or dispatcher shutting down
                _newWorkSemaphore.Wait();

                if (State == DispatcherState.ShuttingDown)
                {
                    foreach (var queue in _queues)
                    {
                        foreach (var item in queue)
                        {
                            item.SignalFinishedWithException(new OperationCanceledException());
                        }
                    }

                    break;
                }

                // Pick highest priority work
                DispatcherItem dispatcherItem = null;
                for (Int32 i = _queues.Length - 1; i >= 0; i--)
                {
                    _queues[i].TryDequeue(out dispatcherItem);
                    if (dispatcherItem != null)
                    {
                        break;
                    }
                }

                // This, actually, should never happen
                if (dispatcherItem == null)
                {
                    throw new DispatcherException("Work is null");
                }

                // Execute user action
                try
                {
                    if (dispatcherItem.DelegateWithoutResult != null)
                    {
                        dispatcherItem.DelegateWithoutResult.Invoke();
                        dispatcherItem.SignalFinished();
                    }
                    else
                    {
                        var result = dispatcherItem.DelegateWithResult.Invoke();
                        dispatcherItem.SignalFinished(result);
                    }
                }
                catch (Exception ex)
                {
                    dispatcherItem.SignalFinishedWithException(ex);
                }
            }

            _shutdownTaskCompletionSource.SetResult(null);
        }
        public void Stop()
        {
            lock (_lock)
            {
                if (_state != DispatcherState.Running)
                    return;

                _state = DispatcherState.Closing;
            }
        }
        public void Start()
        {
            lock (_lock)
            {
                if (_state == DispatcherState.Running)
                    throw new InvalidOperationException("The dispatcher is already running.");

                if(_state == DispatcherState.Closing) {
                    _state = DispatcherState.Running;
                } else {
                    _state = DispatcherState.Running;
                    _thread = new Thread(Run) { IsBackground = false };
                    _thread.Start();
                }
            }
        }
        public void Stop()
        {
            lock (_lock)
            {
                if (_state != DispatcherState.Running)
                    throw new InvalidOperationException("The dispatcher is already stoped.");

                _state = DispatcherState.Closing;
            }
        }
Exemple #39
0
        /// <summary>
        /// Handle a socket accept
        /// </summary>
        private void AcceptSocket(IAsyncResult result)
        {
            State = DispatcherState.AcceptingSocket;
            Socket sock = m_listener.EndAcceptSocket(result);

            //Queue the next accept
            BeginAcceptingSockets();

            //Fire the event handler for sockets
            if (SocketConnected != null)
            {
                SocketConnected(sock);
            }
            else
            {
                //boot the user if nobody is listening
                sock.Disconnect(false);
            }
        }
Exemple #40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Dispatcher"/> class.
        /// Use this if you need to inject a logger, for example for testing
        /// </summary>
        /// <param name="commandProcessor">The command processor.</param>
        /// <param name="messageMapperRegistry">The message mapper registry.</param>
        /// <param name="connections">The connections.</param>
        /// <param name="logger">The logger.</param>
        public Dispatcher(
            IAmACommandProcessor commandProcessor, 
            IAmAMessageMapperRegistry messageMapperRegistry, 
            IEnumerable<Connection> connections,
            ILog logger)
        {
            CommandProcessor = commandProcessor;
            _messageMapperRegistry = messageMapperRegistry;
            this.Connections = connections;
            _logger = logger;
            State = DispatcherState.DS_NOTREADY;

            Consumers = new SynchronizedCollection<IAmAConsumer>();

            State = DispatcherState.DS_AWAITING;
        }
Exemple #41
0
 public Dispatcher()
 {
     TaskLock = new object();
     TaskList = new List <Task>();
     State    = DispatcherState.Terminated;
 }
Exemple #42
0
 public bool Edge(DispatcherState from, DispatcherState to)
 {
     var t = (int) to;
     var f = (int) from;
     return Interlocked.CompareExchange (ref m_state, t, f) == f;
 }
 public Dispatcher()
 {
     _lock = new object();
     _queue = new Queue<Task>();
     _state = DispatcherState.Terminated;
 }
Exemple #44
0
        private void Start()
        {
            _controlTask = Task.Factory.StartNew(() =>
                {
                    if (State == DispatcherState.DS_AWAITING || State == DispatcherState.DS_STOPPED)
                    {
                        _logger.Info("Dispatcher: Dispatcher starting");
                        State = DispatcherState.DS_RUNNING;

                        var consumers = Consumers.ToArray();
                        consumers.Each((consumer) => consumer.Open());
                        consumers.Select(consumer => consumer.Job).Each(job => _tasks.Add(job));

                        _logger.InfoFormat("Dispatcher: Dispatcher starting {0} performers", _tasks.Count);

                        while (_tasks.Any())
                        {
                            try
                            {
                                var index = Task.WaitAny(_tasks.ToArray());
                                _logger.DebugFormat("Dispatcher: Performer stopped with state {0}", _tasks[index].Status);

                                var consumer = Consumers.SingleOrDefault(c => c.JobId == _tasks[index].Id);
                                if (consumer != null)
                                {
                                    _logger.DebugFormat("Dispatcher: Removing a consumer with connection name {0}", consumer.Name);
                                    consumer.Dispose();
                                    Consumers.Remove(consumer);
                                }

                                _tasks[index].Dispose();
                                _tasks.RemoveAt(index);
                            }
                            catch (AggregateException ae)
                            {
                                ae.Handle(
                                    (ex) =>
                                    {
                                        _logger.ErrorFormat("Dispatcher: Error on consumer; consumer shut down");
                                        return true;
                                    });
                            }
                        }

                        State = DispatcherState.DS_STOPPED;
                        _logger.Info("Dispatcher: Dispatcher stopped");
                    }
                },
                TaskCreationOptions.LongRunning);
        }
Exemple #45
0
 /// <summary>
 /// Stop listening for connections
 /// </summary>
 public void Stop()
 {
     m_listener.Stop();
     State = DispatcherState.Stopped;
 }
Exemple #46
0
        private void Start()
        {
            _controlTask = Task.Factory.StartNew(() =>
            {
                if (State == DispatcherState.DS_AWAITING || State == DispatcherState.DS_STOPPED)
                {
                    _logger.Value.Info("Dispatcher: Dispatcher starting");
                    State = DispatcherState.DS_RUNNING;

                    var consumers = Consumers.ToArray();
                    consumers.Each(consumer => consumer.Open());
                    consumers.Each(consumer => _tasks.TryAdd(consumer.JobId, consumer.Job));

                    _logger.Value.InfoFormat("Dispatcher: Dispatcher starting {0} performers", _tasks.Count);

                    while (!_tasks.IsEmpty)
                    {
                        try
                        {
                            var runningTasks = _tasks.Values.ToArray();
                            var index = Task.WaitAny(runningTasks);
                            var stoppingConsumer = runningTasks[index];
                            _logger.Value.DebugFormat("Dispatcher: Performer stopped with state {0}", stoppingConsumer.Status);

                            var consumer = Consumers.SingleOrDefault(c => c.JobId == stoppingConsumer.Id);
                            if (consumer != null)
                            {
                                _logger.Value.DebugFormat("Dispatcher: Removing a consumer with connection name {0}", consumer.Name);
                                consumer.Dispose();

                                _consumers.TryRemove(consumer.Name, out consumer);
                            }

                            //_tasks[index].Dispose();
                            //_tasks.RemoveAt(index);
                            //_tasks.TryTake(out )
                            Task removedTask;
                            _tasks.TryRemove(stoppingConsumer.Id, out removedTask);
                        }
                        catch (AggregateException ae)
                        {
                            ae.Handle(ex =>
                            {
                                _logger.Value.ErrorFormat("Dispatcher: Error on consumer; consumer shut down");
                                return true;
                            });
                        }
                    }

                    State = DispatcherState.DS_STOPPED;
                    _logger.Value.Info("Dispatcher: Dispatcher stopped");
                }
            },
            TaskCreationOptions.LongRunning);
        }
Exemple #47
0
 /// <summary>
 /// Start an async socket accept
 /// </summary>
 private void BeginAcceptingSockets()
 {
     State = DispatcherState.Listening;
     m_listener.BeginAcceptSocket(AcceptSocket, null);
 }