Files

138 lines
3.5 KiB
C#
Raw Permalink Normal View History

2014-10-31 09:05:52 +02:00
using System;
using System.Collections.Generic;
namespace MTApiService
{
internal class MtCommandExecutorManager : ICommandManager
2014-10-31 09:05:52 +02:00
{
#region Public Methods
public void Stop()
{
lock (_locker)
{
_commandExecutors.Clear();
_commandTasks.Clear();
2014-10-31 09:05:52 +02:00
}
}
public void AddCommandExecutor(MtExpert commandExecutor)
{
if (commandExecutor == null)
return;
var notify = false;
2014-10-31 09:05:52 +02:00
lock (_locker)
{
if (_commandExecutors.Contains(commandExecutor))
2014-10-31 09:05:52 +02:00
return;
_commandExecutors.Add(commandExecutor);
if (_commandTasks.Count > 0)
2014-10-31 09:05:52 +02:00
{
notify = true;
2014-10-31 09:05:52 +02:00
}
}
commandExecutor.CommandExecuted += CommandExecutor_CommandExecuted;
commandExecutor.CommandManager = this;
if (notify)
{
NotifyCommandReady();
}
2014-10-31 09:05:52 +02:00
}
public void RemoveCommandExecutor(MtExpert commandExecutor)
{
if (commandExecutor == null)
return;
var notify = false;
2014-10-31 09:05:52 +02:00
lock (_locker)
{
if (_commandExecutors.Contains(commandExecutor) == false)
2014-10-31 09:05:52 +02:00
return;
_commandExecutors.Remove(commandExecutor);
if (_commandTasks.Count > 0)
2014-10-31 09:05:52 +02:00
{
notify = true;
2014-10-31 09:05:52 +02:00
}
}
commandExecutor.CommandExecuted -= CommandExecutor_CommandExecuted;
commandExecutor.CommandManager = null;
if (notify)
{
NotifyCommandReady();
}
2014-10-31 09:05:52 +02:00
}
public void EnqueueCommandTask(MtCommandTask task)
2014-10-31 09:05:52 +02:00
{
if (task == null)
2014-10-31 09:05:52 +02:00
return;
lock (_locker)
{
_commandTasks.Enqueue(task);
2014-10-31 09:05:52 +02:00
}
NotifyCommandReady();
2014-10-31 09:05:52 +02:00
}
public MtCommandTask DequeueCommandTask()
2014-10-31 09:05:52 +02:00
{
lock (_locker)
{
return _commandTasks.Count > 0 ? _commandTasks.Dequeue() : null;
2014-10-31 09:05:52 +02:00
}
}
#endregion
#region Private Methods
private void NotifyCommandReady()
2014-10-31 09:05:52 +02:00
{
var commandExecutors = new List<MtExpert>();
lock (_locker)
{
commandExecutors.AddRange(_commandExecutors);
}
2014-10-31 09:05:52 +02:00
foreach (var executor in commandExecutors)
2014-10-31 09:05:52 +02:00
{
executor.NotifyCommandReady();
2014-10-31 09:05:52 +02:00
}
}
2014-10-31 09:05:52 +02:00
private void CommandExecutor_CommandExecuted(object sender, EventArgs e)
{
var notify = false;
2014-10-31 09:05:52 +02:00
lock (_locker)
{
if (_commandTasks.Count > 0)
2014-10-31 09:05:52 +02:00
{
notify = true;
2014-10-31 09:05:52 +02:00
}
}
if (notify)
{
NotifyCommandReady();
}
2014-10-31 09:05:52 +02:00
}
2014-10-31 09:05:52 +02:00
#endregion
#region Private Fields
private readonly List<MtExpert> _commandExecutors = new List<MtExpert>();
private readonly Queue<MtCommandTask> _commandTasks = new Queue<MtCommandTask>();
2014-10-31 09:05:52 +02:00
private readonly object _locker = new object();
#endregion
}
}