Exemple #1
0
 ///<summary>
 /// Ctor.
 ///</summary>
 ///<param name="taskQueue">The task queue to use.</param>
 ///<param name="eventAggregator">An event aggregator.</param>
 ///<param name="unhandledExceptionPolicy">An exception policy.</param>
 public TaskRunner(ITaskQueue taskQueue, IEventAggregator eventAggregator,
     IUnhandledExceptionPolicy unhandledExceptionPolicy)
 {
     this.taskQueue = taskQueue;
     this.eventAggregator = eventAggregator;
     this.unhandledExceptionPolicy = unhandledExceptionPolicy;
     currentWorkerTasks = new LockBox<IDictionary<string, ThreadTask>>(new Dictionary<string, ThreadTask>());
 }
 protected TaskQueueController(ITaskQueue taskQueue)
 {
     if (taskQueue == null)
     {
         throw new ArgumentNullException("taskQueue");
     }
     _taskQueue = taskQueue;
 }
 public BoundedTaskQueueController(ITaskQueue taskQueue, int maxTasksCount)
     : base(taskQueue)
 {
     if (maxTasksCount < 1)
     {
         throw new ArgumentException("MaxTasksCount should be greater 0");
     }
     _maxTasksCount = maxTasksCount;
 }
Exemple #4
0
        public Voltmeter(IDeviceManager deviceManager, ITaskQueue eventsQueue)
        {
            Contract.Requires<ArgumentNullException>(deviceManager != null);
            Contract.Requires<ArgumentNullException>(eventsQueue != null);

            DeviceManager = deviceManager;
            EventsQueue = eventsQueue;
            Readings = new ElectricReadings();
            Use10BitVoltage = true;
            PollingInterval = DeviceConstants.MinPollingInterval;
        }
Exemple #5
0
 public BestPortWrapper(
     ILogger logger,
     ITaskQueue taskQueue,
     PingableOpenVpnPort pingableOpenVpnPort,
     ISingleVpnConnection origin)
 {
     _logger = logger;
     _pingableOpenVpnPort = pingableOpenVpnPort;
     _origin               = origin;
     _taskQueue            = taskQueue;
     _origin.StateChanged += Origin_StateChanged;
 }
        public IProcessor Create(ProcessorConfiguration configuration, ITaskQueue taskQueue)
        {
            var localDirectoryObject = new LocalDirectoryObject(configuration.LocalDirectory);

            var amazonS3Client = _amazonS3ClientFactory.GetS3Client(configuration);

            amazonS3Client.BeforeRequestEvent += AmazonS3Client_BeforeRequestEvent;
            amazonS3Client.AfterResponseEvent += AmazonS3Client_AfterResponseEvent;
            var s3DirectoryObject = new S3DirectoryObject(amazonS3Client, configuration.S3Bucket);

            return(new Processor(localDirectoryObject, s3DirectoryObject, taskQueue));
        }
        public BackupController(CancellationToken cancel, IBackupManager backupmgr, INameService namesvc, IPersistentStorage pstore, ITaskQueue taskqueue)
        {
            this.m_backupmgr = backupmgr;
            this.m_cancel    = cancel;
            this.m_dmc       = Global.CloudStorage as DynamicMemoryCloud;
            this.m_namesvc   = namesvc;
            this.m_pstore    = pstore;
            this.m_taskqueue = taskqueue;

            m_backupmgr.RequestPartitionBackup  += OnBackupManagerRequestBackup;
            m_backupmgr.RequestPartitionRestore += OnBackupManagerRequestRestore;
        }
        public ReconnectingWrapper(
            ILogger logger,
            ITaskQueue taskQueue,
            IVpnEndpointCandidates candidates,
            ISingleVpnConnection origin)
        {
            _logger     = logger;
            _taskQueue  = taskQueue;
            _candidates = candidates;
            _origin     = origin;

            _origin.StateChanged += Origin_StateChanged;
        }
Exemple #9
0
        public static T ExecuteAndWait <T>(this ITaskQueue queue, Func <CancellationToken, T> task)
        {
            var result = default(T);
            var e      = new ManualResetEvent(false);

            queue.ExecuteAsync(token => {
                result = task(token);
                e.Set();
            });
            e.WaitOne();
            Invariants.Assert(result != null);
            return(result);
        }
Exemple #10
0
        protected TTaskThread StartThread(ITaskQueue <TMessage> queue, ILog log)
        {
            TTaskThread obj    = CreateTaskThread(queue, log);
            Thread      thread = new Thread(obj.HandleTask);

            thread.IsBackground = true;
            obj.SetThread(thread);

            log.InfoFormat("【{0}_{1}】任务处理线程已开启...", queue.TaskQueueType, queue.TaskQueueIndex.ToString());

            thread.Start();
            return(obj);
        }
        /// <summary>
        /// Cancel the task with the specified tag.
        /// <param name="tag"></param>
        /// </summary>
        public static ITaskQueue <TTaskInfo> Deschedule <TTaskInfo>(this ITaskQueue <TTaskInfo> source, string tag)
            where TTaskInfo : TaskInfo
        {
            var context = source.GetSchedulerContext();
            var queue   = context.Queue;
            var item    = queue.FirstOrDefault(x => x.Tag == tag);

            if (item == null)
            {
                throw new InvalidOperationException($"Task with tag \"{tag}\" does not exist.");
            }
            return((ITaskQueue <TTaskInfo>)source.Deschedule(item));
        }
Exemple #12
0
 public VpnConnectionHandler(
     KillSwitch.KillSwitch killSwitch,
     IVpnConnection vpnConnection,
     ILogger logger,
     IServiceSettings serviceSettings,
     ITaskQueue taskQueue)
 {
     _killSwitch                  = killSwitch;
     _vpnConnection               = vpnConnection;
     _logger                      = logger;
     _serviceSettings             = serviceSettings;
     _taskQueue                   = taskQueue;
     _vpnConnection.StateChanged += VpnConnection_StateChanged;
 }
Exemple #13
0
        public CTaskQueue()
        {
            switch (ConfigurationManager.AppSettings["utils.taskqueue.impl"])
            {
            case "sqs":
                m_oTaskQueue = new CTaskQueueAmazonSQS();
                break;

            case "db":
            default:
                m_oTaskQueue = new CTaskQueueDataBase();
                break;
            }
        }
Exemple #14
0
        public JobScheduler(
            [Dependency]
            ITaskQueue taskQueue,
            [Dependency]
            IJobBuildingPipeline jobBuildingPipeline)
        {
            Contract.Requires(taskQueue != null);
            Contract.Requires(jobBuildingPipeline != null);
            Contract.Ensures(this.taskQueue != null);
            Contract.Ensures(this.jobBuildingPipeline != null);

            this.taskQueue = taskQueue;
            this.jobBuildingPipeline = jobBuildingPipeline;
        }
        protected T Create <T>(T concrete, ITaskQueue queue) where T : class
        {
            var cached = CheckInCache(concrete);

            if (cached != null)
            {
                return(cached);
            }

            var interceptors = new IInterceptor[] { new QueueDispatcherInterceptor(queue) };
            var res          = _Generator.CreateInterfaceProxyWithTargetInterface <T>(concrete, interceptors);

            Register(concrete, res, queue);
            return(res);
        }
        private static BaseCompressConsumer <DataPortion> GetConsumer(
            CompressionMode mode, ITaskQueue <DataPortion> forCompressingTaskQueue)
        {
            BaseCompressConsumer <DataPortion> consumer;

            if (mode == CompressionMode.Compress)
            {
                consumer = new CompressConsumer(forCompressingTaskQueue.Tasks);
            }
            else
            {
                consumer = new DecompressConsumer(forCompressingTaskQueue.Tasks);
            }
            return(consumer);
        }
Exemple #17
0
        /// <summary>
        /// Initialization
        /// </summary>
        /// <param name="inputFile">Input file</param>
        /// <param name="sizeBlock">Size of block</param>
        /// <param name="fileResult">File of result</param>
        public void Init(string inputFile, string sizeBlock, string fileResult = "SignatureBlocks.txt")
        {
            if (!int.TryParse(sizeBlock, out int sizeOfBlock))
            {
                throw new ArgumentException("Size of block must be integer value");
            }

            _fileSource = new FileSource();
            _fileSource.Open(inputFile, sizeOfBlock);
            TaskCalcHashSha256.Source = _fileSource;

            TaskWriteObjectToFile.FileName = Path.Combine(Environment.CurrentDirectory, fileResult);

            _taskQueue = new TaskQueue();
            _taskQueue.Init(true);
        }
        /// <summary>
        /// Waits for the queue to be stopped.
        /// </summary>
        /// <returns>The current queue.</returns>
        public static async Task <ITaskQueue> AwaitIsStopped(this ITaskQueue source)
        {
            if (source.IsStopped)
            {
                return(source);
            }
            EventHandler <QueueEventArgs> handler = null;
            var tcs = new TaskCompletionSource <ITaskQueue>();

            handler = (s, e) => {
                source.Stopped -= handler;
                tcs.SetResult(source);
            };
            source.Stopped += handler;
            return(await tcs.Task);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="LocalizationService" /> class.
        /// </summary>
        /// <param name="settingsService">The settings service.</param>
        /// <param name="eventAggregator">The event aggregator.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="taskQueue">The task queue.</param>
        /// <param name="dispatcher">The dispatcher.</param>
        public LocalizationService(ISettingsService settingsService, IEventAggregator eventAggregator, ILogger logger, ITaskQueue taskQueue, IDispatcher dispatcher)
            : base(logger)
        {
            _systemFormat    = Thread.CurrentThread.CurrentCulture.DateTimeFormat;
            _settingsService = settingsService;
            _settingsType    = SettingsDataType.Localization;

            _taskQueue  = taskQueue;
            _dispatcher = dispatcher;

            _localizationChangedEvent  = eventAggregator.GetEvent <LocalizationChangedEvent>();
            _localizationChangingEvent = eventAggregator.GetEvent <LocalizationChangingEvent>();

            Languages = EnumHelper.GetValues <Language>().OrderBy(x => x.GetOrder()).Select(e => new LanguageInfo(e)).ToArray();

            eventAggregator.GetEvent <ChangeLocaleEvent>().Subscribe(OnChangeLocaleEvent, ThreadOption.UIThread);
        }
        /// <summary>
        /// Waits for the queue to be empty.
        /// </summary>
        /// <returns>The current queue.</returns>
        public static async Task <ITaskQueue <TTaskInfo> > AwaitIsEmpty <TTaskInfo>(this ITaskQueue <TTaskInfo> source)
            where TTaskInfo : TaskInfo
        {
            if (source.IsEmpty)
            {
                return(source);
            }
            EventHandler <QueueEventArgs> handler = null;
            var tcs = new TaskCompletionSource <ITaskQueue <TTaskInfo> >();

            handler = (s, e) => {
                source.Empty -= handler;
                tcs.SetResult(source);
            };
            source.Empty += handler;
            return(await tcs.Task);
        }
 public FileSystemProcessor(
     IFileSystemNameFactory fileSystemNameFactory,
     IProjectDiscovery projectDiscovery,
     IDirectoryChangeWatcherFactory directoryChangeWatcherFactory,
     ITaskQueueFactory taskQueueFactory,
     IFileSystemSnapshotBuilder fileSystemSnapshotBuilder,
     IOperationProcessor<SnapshotComputedEventArgs> snapshotOperationProcessor)
 {
     _fileSystemNameFactory = fileSystemNameFactory;
       _directoryChangeWatcher = directoryChangeWatcherFactory.CreateWatcher();
       _fileSystemSnapshotBuilder = fileSystemSnapshotBuilder;
       _snapshotOperationProcessor = snapshotOperationProcessor;
       _projectDiscovery = projectDiscovery;
       _taskQueue = taskQueueFactory.CreateQueue();
       _directoryChangeWatcher.PathsChanged += DirectoryChangeWatcherOnPathsChanged;
       _fileSystemSnapshot = FileSystemTreeSnapshot.Empty;
 }
 public FileSystemProcessor(
     IFileSystemNameFactory fileSystemNameFactory,
     IProjectDiscovery projectDiscovery,
     IDirectoryChangeWatcherFactory directoryChangeWatcherFactory,
     ITaskQueueFactory taskQueueFactory,
     IFileSystemSnapshotBuilder fileSystemSnapshotBuilder,
     IOperationProcessor <SnapshotComputedEventArgs> snapshotOperationProcessor)
 {
     _fileSystemNameFactory      = fileSystemNameFactory;
     _directoryChangeWatcher     = directoryChangeWatcherFactory.CreateWatcher();
     _fileSystemSnapshotBuilder  = fileSystemSnapshotBuilder;
     _snapshotOperationProcessor = snapshotOperationProcessor;
     _projectDiscovery           = projectDiscovery;
     _taskQueue = taskQueueFactory.CreateQueue();
     _directoryChangeWatcher.PathsChanged += DirectoryChangeWatcherOnPathsChanged;
     _fileSystemSnapshot = FileSystemTreeSnapshot.Empty;
 }
        protected T CreateIActorLifeCycle <T>(T concrete, ITaskQueue queue, Type addicionalType, params IInterceptor[] interceptor) where T : class
        {
            var cached = CheckInCache(concrete);

            if (cached != null)
            {
                return(cached);
            }

            var interceptors = new List <IInterceptor>(interceptor);

            interceptors.Add(new QueueDispatcherInterceptor(queue));
            var res = (T)_Generator.CreateInterfaceProxyWithTargetInterface(typeof(T), new Type[] { addicionalType }, concrete, interceptors.ToArray());

            Register(concrete, res, queue);
            return(res);
        }
Exemple #24
0
        public TaskProvider(
            [Dependency]
            ITaskQueue taskQueue,
            [Dependency]
            ISchedulerConfiguration schedulerConfiguration)
        {
            Contract.Requires(taskQueue != null);
            Contract.Ensures(this.taskQueue == taskQueue);

            this.taskQueue = taskQueue;
            var operationContext = OperationContext.Current;
            WcfPerfomance.MonitorEvents(operationContext, "TaskProvider");

            operationContext.Channel.Faulted += OnChannelFaulted;
            operationContext.Channel.Closing += OnChannelClosing;

            pingTimeout = schedulerConfiguration.TaskProvider.PingTimeout;
        }
        /// <summary>
        /// Create thread pool.
        /// </summary>
        /// <param name="name">
        /// Name of the thread pool.
        /// 
        /// <remarks>
        /// Thread pool will assign underlying threads names, that mind help in debugging.
        /// </remarks>
        /// </param>
        /// <param name="maxThreadCount">
        /// Maximum threads count.
        /// </param>
        /// <param name="taskQueueFactory">
        /// <see cref="ITaskQueue">ITaskQueue</see> factory function.
        /// <remarks>
        /// Provide particular ITaskQueue to change task scheduling strategy.
        /// Please note that task queue ensures only dequeing order of tasks, task execution itself 
        /// can be slightly of-order in multithreading environment.
        /// Task queue should returned by this functions not be thread safe, but it also should not be 
        /// accessed from anywhere in program outside from the FixedThreadPool instance. Please
        /// ensure that function returns a new instance of ITaskQueue on each call.
        /// </remarks>
        /// </param>
        /// <param name="forceThreadCreation">
        /// boolean flag indicating whether create threads in advance or by need.
        /// </param>
        public FixedThreadPool(string name, int maxThreadCount, Func<ITaskQueue> taskQueueFactory, bool forceThreadCreation)
        {
            if (maxThreadCount <= 0) throw new ArgumentOutOfRangeException("maxThreadCount", "Maximum thread count should be greater than zero.");
            if (taskQueueFactory == null) throw new ArgumentNullException("taskQueueFactory");

            m_DeferedThreadCount = maxThreadCount;
            m_MaxThreadCount = maxThreadCount;
            m_Name = name;
            m_TaskQueue = taskQueueFactory();

            if (forceThreadCreation)
            {
                for (var i = 0; i < MaxThreadCount; i++)
                {
                    ThreadNeeded();
                }
            }
        }
Exemple #26
0
        public Ipv6HandlingWrapper(
            IServiceSettings serviceSettings,
            IFirewall firewall,
            ObservableNetworkInterfaces networkInterfaces,
            Ipv6 ipv6,
            ITaskQueue taskQueue,
            IVpnConnection origin)
        {
            _serviceSettings = serviceSettings;
            _firewall        = firewall;
            _ipv6            = ipv6;
            _taskQueue       = taskQueue;
            _origin          = origin;

            _origin.StateChanged                     += Origin_StateChanged;
            _serviceSettings.SettingsChanged         += OnServiceSettingsChanged;
            networkInterfaces.NetworkInterfacesAdded += NetworkInterfaces_NetworkInterfacesAdded;
        }
Exemple #27
0
        public IndexingServer(
            IDateTimeProvider dateTimeProvider,
            IFileSystemSnapshotManager fileSystemSnapshotManager,
            ITaskQueueFactory taskQueueFactory,
            ISearchEngine searchEngine)
        {
            _dateTimeProvider          = dateTimeProvider;
            _fileSystemSnapshotManager = fileSystemSnapshotManager;
            _stateChangeTaskQueue      = taskQueueFactory.CreateQueue("IndexingServer State Change Task Queue");

            _fileSystemSnapshotManager.SnapshotScanStarted    += FileSystemSnapshotManagerOnSnapshotScanStarted;
            _fileSystemSnapshotManager.SnapshotScanFinished   += FileSystemSnapshotManagerOnSnapshotScanFinished;
            _fileSystemSnapshotManager.FileSystemWatchPaused  += FileSystemSnapshotManagerOnFileSystemWatchPaused;
            _fileSystemSnapshotManager.FileSystemWatchResumed += FileSystemSnapshotManagerOnFileSystemWatchResumed;

            searchEngine.FilesLoading += SearchEngineOnFilesLoading;
            searchEngine.FilesLoaded  += SearchEngineOnFilesLoaded;
            _currentState              = GetCurrentState();
        }
        public FileSystemProcessor(
            IFileSystemNameFactory fileSystemNameFactory,
            IFileSystem fileSystem,
            IFileSystemSnapshotBuilder fileSystemSnapshotBuilder,
            IOperationProcessor operationProcessor,
            IProjectDiscovery projectDiscovery,
            IDirectoryChangeWatcherFactory directoryChangeWatcherFactory,
            ITaskQueueFactory taskQueueFactory)
        {
            _fileSystemNameFactory = fileSystemNameFactory;
              _fileSystem = fileSystem;
              _fileSystemSnapshotBuilder = fileSystemSnapshotBuilder;
              _operationProcessor = operationProcessor;
              _projectDiscovery = projectDiscovery;

              _taskQueue = taskQueueFactory.CreateQueue("FileSystemProcessor Task Queue");
              _fileSystemSnapshot = FileSystemTreeSnapshot.Empty;
              _directoryChangeWatcher = directoryChangeWatcherFactory.CreateWatcher();
              _directoryChangeWatcher.PathsChanged += DirectoryChangeWatcherOnPathsChanged;
        }
Exemple #29
0
        public override SchedulerContext <TaskInfo> GetContext(ITaskQueue <TaskInfo> taskQueue, ITaskCollection <TaskInfo> items, CancellationTokenSource cts, SchedulerContextData queueData)
        {
            return(new SchedulerContext <TaskInfo>(items, cts)
            {
                Delay = taskQueue.Delay,
                CancelOnException = taskQueue.CancelOnException,

                _queueEmpty = queueData._queueEmpty,

                _queueStarted = queueData._queueStarted,
                _queueStopped = queueData._queueStopped,

                _taskScheduled = queueData._taskScheduled,
                _taskCanceled = queueData._taskCanceled,
                _taskCanceling = queueData._taskCanceling,
                _taskExecuting = queueData._taskExecuting,
                _taskExecuted = queueData._taskExecuted,
                _taskException = queueData._taskException
            });
        }
Exemple #30
0
        public Smtp4devServer(IServiceScopeFactory serviceScopeFactory, IOptionsMonitor <ServerOptions> serverOptions,
                              IOptionsMonitor <RelayOptions> relayOptions, NotificationsHub notificationsHub, Func <RelayOptions, SmtpClient> relaySmtpClientFactory,
                              ITaskQueue taskQueue)
        {
            this.notificationsHub       = notificationsHub;
            this.serverOptions          = serverOptions;
            this.relayOptions           = relayOptions;
            this.serviceScopeFactory    = serviceScopeFactory;
            this.relaySmtpClientFactory = relaySmtpClientFactory;
            this.taskQueue = taskQueue;

            DoCleanup();

            IDisposable eventHandler = null;
            var         obs          = Observable.FromEvent <ServerOptions>(e => eventHandler = serverOptions.OnChange(e), e => eventHandler.Dispose());

            obs.Throttle(TimeSpan.FromMilliseconds(100)).Subscribe(OnServerOptionsChanged);

            taskQueue.Start();
        }
Exemple #31
0
        public override bool Open(ClusterConfig config, bool nonblocking)
        {
            this.m_cluster_config = config;
            m_cancelSrc           = new CancellationTokenSource();
            m_nameservice         = AssemblyUtility.GetAllClassInstances <INameService>().First();
            Log.WriteLine(LogLevel.Info, $"{nameof(DynamicMemoryCloud)}: using name service provided by '{m_nameservice.GetType().FullName}'");
            m_chunktable = AssemblyUtility.GetAllClassInstances <IChunkTable>().First();
            Log.WriteLine(LogLevel.Info, $"{nameof(DynamicMemoryCloud)}: using chunk table provided by '{m_chunktable.GetType().FullName}'");
            m_taskqueue = AssemblyUtility.GetAllClassInstances <ITaskQueue>().First();
            Log.WriteLine(LogLevel.Info, $"{nameof(DynamicMemoryCloud)}: using task queue provided by '{m_taskqueue.GetType().FullName}'");
            m_healthmanager = AssemblyUtility.GetAllClassInstances <IHealthManager>().First();
            Log.WriteLine(LogLevel.Info, $"{nameof(DynamicMemoryCloud)}: using health manager provided by '{m_healthmanager.GetType().FullName}'");
            m_backupmgr = AssemblyUtility.GetAllClassInstances <IBackupManager>().First();
            Log.WriteLine(LogLevel.Info, $"{nameof(DynamicMemoryCloud)}: using backup manager provided by '{m_backupmgr.GetType().FullName}'");
            m_persistent_storage = AssemblyUtility.GetAllClassInstances <IPersistentStorage>().First();
            Log.WriteLine(LogLevel.Info, $"{nameof(DynamicMemoryCloud)}: using persistent storage provided by '{m_persistent_storage.GetType().FullName}'");

            m_nameservice.Start(m_cancelSrc.Token);
            m_taskqueue.Start(m_cancelSrc.Token);
            m_chunktable.Start(m_cancelSrc.Token);
            m_healthmanager.Start(m_cancelSrc.Token);
            m_backupmgr.Start(m_cancelSrc.Token);

            m_myid                 = GetInstanceId(InstanceGuid);
            m_storageTable         = new DynamicStorageTable(PartitionCount);
            m_storageTable[m_myid] = Global.LocalStorage;
            NickName               = GenerateNickName(InstanceGuid);

            int redundancy = DynamicClusterConfig.Instance.MinimumReplica;

            m_cloudidx    = new CloudIndex(m_cancelSrc.Token, m_nameservice, m_chunktable, this, NickName, PartitionTable);
            m_healthmon   = new HealthMonitor(m_cancelSrc.Token, m_nameservice, m_cloudidx, m_healthmanager, redundancy);
            m_partitioner = new Partitioner(m_cancelSrc.Token, m_cloudidx, m_nameservice, m_taskqueue, DynamicClusterConfig.Instance.ReplicationMode, redundancy);
            m_taskexec    = new Executor(m_cancelSrc.Token, m_nameservice, m_taskqueue);
            m_backupctl   = new BackupController(m_cancelSrc.Token, m_backupmgr, m_nameservice, m_persistent_storage, m_taskqueue);

            Log.WriteLine($"{nameof(DynamicMemoryCloud)}: Partition {MyPartitionId}: Instance '{NickName}' {InstanceGuid} opened.");
            Global.CommunicationInstance.Started += InitModule;

            return(true);
        }
        public FileSystemProcessor(
            IFileSystemNameFactory fileSystemNameFactory,
            IFileSystem fileSystem,
            IFileSystemSnapshotBuilder fileSystemSnapshotBuilder,
            IOperationProcessor operationProcessor,
            IProjectDiscovery projectDiscovery,
            IDirectoryChangeWatcherFactory directoryChangeWatcherFactory,
            ITaskQueueFactory taskQueueFactory)
        {
            _fileSystemNameFactory     = fileSystemNameFactory;
            _fileSystem                = fileSystem;
            _fileSystemSnapshotBuilder = fileSystemSnapshotBuilder;
            _operationProcessor        = operationProcessor;
            _projectDiscovery          = projectDiscovery;

            _taskQueue              = taskQueueFactory.CreateQueue("FileSystemProcessor Task Queue");
            _fileSystemSnapshot     = FileSystemTreeSnapshot.Empty;
            _directoryChangeWatcher = directoryChangeWatcherFactory.CreateWatcher();
            _directoryChangeWatcher.PathsChanged += DirectoryChangeWatcherOnPathsChanged;
            _directoryChangeWatcher.Error        += DirectoryChangeWatcherOnError;
        }
Exemple #33
0
        /// <summary>
        /// 添加一个对象到管理器中,并让这个对象开始接收消息
        /// </summary>
        /// <param name="queue"></param>
        /// <returns> 返回管理器为对象分配的 task ID </returns>
        /// <exception cref="ArgumentNullException"> 当 <paramref name="queue"/> 传入 null 时引发 </exception>
        public long AddTaskQueue(ITaskQueue queue)
        {
            if (queue == null)
            {
                throw new ArgumentNullException("queue");
            }
            long taskId = 0;

            lock (pool) {
                while (pool.ContainsKey(++taskId))
                {
                }
                var end  = new System.Threading.CancellationTokenSource();
                var info = new TaskQueueInfo()
                {
                    queue = queue,
                    end   = end,
                    task  = Task.Run(() => { }, end.Token),
                };
                pool.Add(taskId, info);
            }
            return(taskId);
        }
Exemple #34
0
        public SearchEngine(
            IFileSystemSnapshotManager fileSystemSnapshotManager,
            IFileSystemNameFactory fileSystemNameFactory,
            ILongRunningFileSystemTaskQueue taskQueue,
            IFileDatabaseSnapshotFactory fileDatabaseSnapshotFactory,
            IProjectDiscovery projectDiscovery,
            ICompiledTextSearchDataFactory compiledTextSearchDataFactory,
            IOperationProcessor operationProcessor)
        {
            _fileSystemNameFactory         = fileSystemNameFactory;
            _taskQueue                     = taskQueue;
            _fileDatabaseSnapshotFactory   = fileDatabaseSnapshotFactory;
            _projectDiscovery              = projectDiscovery;
            _compiledTextSearchDataFactory = compiledTextSearchDataFactory;
            _operationProcessor            = operationProcessor;

            // Create a "Null" state
            _currentFileDatabase = _fileDatabaseSnapshotFactory.CreateEmpty();

            // Setup computing a new state everytime a new tree is computed.
            fileSystemSnapshotManager.SnapshotScanFinished += FileSystemSnapshotManagerOnSnapshotScanFinished;
            fileSystemSnapshotManager.FilesChanged         += FileSystemSnapshotManagerOnFilesChanged;
        }
Exemple #35
0
        public SearchEngine(
            IFileSystemProcessor fileSystemProcessor,
            IFileSystemNameFactory fileSystemNameFactory,
            ITaskQueueFactory taskQueueFactory,
            IFileDatabaseFactory fileDatabaseFactory,
            IProjectDiscovery projectDiscovery,
            ICompiledTextSearchDataFactory compiledTextSearchDataFactory,
            IOperationProcessor operationProcessor)
        {
            _fileSystemNameFactory         = fileSystemNameFactory;
            _taskQueue                     = taskQueueFactory.CreateQueue("SearchEngine Task Queue");
            _fileDatabaseFactory           = fileDatabaseFactory;
            _projectDiscovery              = projectDiscovery;
            _compiledTextSearchDataFactory = compiledTextSearchDataFactory;
            _operationProcessor            = operationProcessor;

            // Create a "Null" state
            _currentFileDatabase = _fileDatabaseFactory.CreateEmpty();

            // Setup computing a new state everytime a new tree is computed.
            fileSystemProcessor.SnapshotComputed += FileSystemProcessorOnSnapshotComputed;
            fileSystemProcessor.FilesChanged     += FileSystemProcessorOnFilesChanged;
        }
 /// <summary>
 /// Removes the specified queue from the queue collection.
 /// </summary>
 /// <param name="queue"></param>
 /// <returns></returns>
 public static bool Remove(ITaskQueue queue)
 => _queues.Remove(queue.Tag);
Exemple #37
0
 public LongRunningFileSystemTaskQueue(ITaskQueueFactory taskQueueFactory)
 {
     _taskQueue = taskQueueFactory.CreateQueue("Long Running FileSystem Task Queue");
 }
Exemple #38
0
        public IEnumerator Init(bool block)
        {
            if (s_initInProgress)
            {
                CoreLogger.LogError(LoggerModules.GameApplication, "attempt to initialize kernel while already doing so!");
                yield break;
            }

            Application.targetFrameRate = this.targetFrameRate;

            s_instance = this;

            s_initInProgress = true;

            _taskQueue        = gameObject.AddMissingComponent <TaskQueue>();
            _taskQueue.Active = false;

            EnqueueCreateResolvers();

            EnqueueAddProviders();

            EnqueuePreStageServiceResolution(block);
            _taskQueue.Enqueue(() => {
                LoadLoggerConfig();
            });
            EnqueueInitModules(int.MinValue, -1, block);

            EnqueueServiceResolution(block);
            EnqueueInitModules(0, 0, block);

            EnqueuePostStageServiceResolution(block);
            EnqueueInitModules(1, int.MaxValue, block);

            _taskQueue.Enqueue(() => {
                LoadLoggerConfig();
            });

            //register to the event that tells us when the queue is empty,
            //which implies we have finished initializing
            bool initDone = false;

            //when the task queue empties, we will know we are done
            _taskQueue.Enqueue(() => {
                //at this point we can set the static instance safely
                s_earlyAccess = false;

                //init is done
                s_initInProgress = false;
                initDone         = true;
            });

            //now start the actual initialization, by activating the queue
            float initStart = Time.time;

            //start running the init tasks
            _taskQueue.Active = true;

            if (block)
            {
                //the synchronous version:
                _taskQueue.HandleAll();

                //at this point in time, the singleton is ready for use
                _gameModules.Start();

                yield break;
            }
            else
            {
                //the async. version:

                //while(Time.time - initStart < initTimeout)
                while (true)
                {
                    if (Time.time - initStart > initTimeout)
                    {
                        CoreLogger.LogWarning(LoggerModules.GameApplication, "timeout in creating GameApplication object");
                    }

                    if (initDone)
                    {
                        //at this point in time, the singleton is ready for use
                        _gameModules.Start();

                        yield return(StartCoroutine(WaitForStrangeServiceProviderInit()));

                        InitDone();
                        CoreLogger.LogDebug(LoggerModules.GameApplication, "GameApplication succesfully finished Init!");
                        yield break;
                    }

                    yield return(null);
                }
            }
        }
Exemple #39
0
 ///<summary>
 /// Default constructor.
 ///</summary>
 ///<param name="taskQueue">A task queue.</param>
 ///<param name="taskRunner">A task runner.</param>
 public TaskManager(ITaskQueue taskQueue, ITaskRunner taskRunner)
 {
     this.taskQueue = taskQueue;
     this.taskRunner = taskRunner;
 }
 public virtual void InitializeFrom(ITaskQueue otherQueue)
 {
     var tasks = otherQueue.GetAll();
     queueStorage.Init(tasks);
 }
 public void SetUp() 
 {
     taskQueue = MockRepository.GenerateStub<ITaskQueue>();
     taskRunner = MockRepository.GenerateStub<ITaskRunner>();
     taskManager = new TaskManager(taskQueue, taskRunner);
 }
 public TaskExecutorBehavior(ITaskQueue taskQueue)
 {
     _taskQueue = taskQueue;
 }
 public DefaultTaskQueueController(ITaskQueue taskQueue)
     : base(taskQueue)
 {
 }
 public ViewThreadEndpoint(IDocumentSession session, IMappingEngine mapper, ITaskQueue taskQueue)
 {
     _session = session;
     _mapper = mapper;
     _taskQueue = taskQueue;
 }
 public TaskQueueController([FromServices] ITaskQueue TaskQueue)
 {
     _TaskQueue = TaskQueue;
 }
        public CTaskQueue()
        {
            switch (ConfigurationManager.AppSettings["utils.taskqueue.impl"])
            {
                case "sqs":
                    m_oTaskQueue = new CTaskQueueAmazonSQS();
                    break;

                case "db":
                default:
                    m_oTaskQueue = new CTaskQueueDataBase();
                    break;
            }
        }