123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace WingServerCommon.Utilities.Executors
- {
- /// <summary>
- /// The DynamicExecutor provide the ability that can active one worker and let it run first.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public class DynamicExecutor<T> : ExecutorBase<T> where T : class, IIdContext
- {
- private readonly List<ExecuteWorker<T>> _workers = new List<ExecuteWorker<T>>();
- public DynamicExecutor(string name) : base(name)
- {
- }
- protected DynamicExecutor(string name, TimeSpan executeDelayTime) : base(name, executeDelayTime)
- {
- }
- /// <summary>
- /// Activate one worker so that it can run first.
- /// </summary>
- /// <param name="contextId"></param>
- public void ActivateWorker(string contextId)
- {
- lock (WorkersLocker)
- {
- var worker = _workers.FirstOrDefault(x => x.Parameter.Id == contextId);
- if (worker != null && _workers.IndexOf(worker) != 0)
- {
- _workers.Remove(worker);
- _workers.Insert(0, worker);
- }
- }
- }
- /// <summary>
- /// Indicate whether all works already contain the item.
- /// </summary>
- /// <param name="contextId">context id.</param>
- /// <returns>True if contains.</returns>
- public bool ContainsWorker(string contextId)
- {
- lock (WorkersLocker)
- {
- return _workers.Any(m => m.Parameter.Id == contextId);
- }
- }
- /// <summary>
- /// Gets current worker count in queue.
- /// </summary>
- /// <returns></returns>
- protected override int GetWorkerCount()
- {
- return _workers.Count;
- }
- /// <summary>
- /// Add one worker into the queue.
- /// </summary>
- /// <param name="worker"></param>
- protected override void AddWorker(ExecuteWorker<T> worker)
- {
- _workers.Add(worker);
- }
- /// <summary>
- /// Take one worker from the queue.
- /// </summary>
- /// <returns></returns>
- protected override ExecuteWorker<T> TakeWorker()
- {
- var worker = _workers.FirstOrDefault();
- if (worker != null)
- {
- _workers.Remove(worker);
- }
- return worker;
- }
- /// <summary>
- /// Gets all workers.
- /// </summary>
- /// <returns></returns>
- protected override IEnumerable<ExecuteWorker<T>> GetWorkers()
- {
- return _workers.ToArray();
- }
- /// <summary>
- /// Clear all workers which not stated.
- /// </summary>
- protected override void CancelWorkers()
- {
- _workers.Clear();
- }
- }
- }
|