public void putWork(IWork work)
 {
     lock (_syncWorks)
     {
         _works.Add(work);
     }
 }
 void closeDialog(NavigationContext context)
 {
     currentBackgroundTask = null;
     var screenMgr = ServiceRegistration.Get<IScreenManager>();
     if (screenMgr.TopmostDialogInstanceId == context.DialogInstanceId)
         screenMgr.CloseTopmostDialog();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="WorkSucceededProcessingEventArgs"/> class.
        /// </summary>
        /// 
        /// <param name="work">
        /// The item of <see cref="IWork"/> that has been successfully processed.
        /// </param>
        /// 
        /// <exception cref="ArgumentException">
        /// If <paramref name="work"/> is null.
        /// </exception>
        public WorkSucceededProcessingEventArgs(IWork work)
        {
            if (work == null)
                throw new ArgumentException("Argument: 'work' may not be null.");

            this.Work = work;
        }
示例#4
0
        private IWorkItem UpdateWorkItem(IWork work, string value, string[] options)
        {
            var items = value.Split(' ');

            if (items.Length != 2)
            {
                return(null);
            }
            var actor  = items[0].Trim();
            var answer = items[1].Trim();

            answer = options.FirstOrDefault(x => String.Compare(x, answer, StringComparison.OrdinalIgnoreCase) == 0);
            if (answer == null)
            {
                return(null);
            }

            var wi = work.WorkItems.SingleOrDefault(x => String.Compare(x.Participant.Name, actor, StringComparison.OrdinalIgnoreCase) == 0);

            if (wi == null)
            {
                return(null);
            }
            wi.Outcome = answer;
            return(wi);
        }
示例#5
0
        public static string ToJson(IWork work)
        {
            if (work == null)
                throw new ArgumentNullException(nameof(work));

            return JsonConvert.SerializeObject(work, Formatting.None, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });
        }
示例#6
0
 public ClientHelper(Random rand, ListBox logger, IWork work)
 {
     this.rand = rand;
     this.logger = logger;
     this.response = new StringBuilder(200);
     this.work = work;
 }
示例#7
0
        public static byte[] Serialize(IWork work)
        {
            if (work == null)
                throw new ArgumentNullException(nameof(work));

            return Encoding.UTF8.GetBytes(WorkSerializer.ToJson(work));
        }
示例#8
0
            /// <summary>
            /// Adds the given element to the collection
            /// </summary>
            /// <param name="item">The item to add</param>
            public override void Add(IModelElement item)
            {
                if ((this._parent.Organisation == null))
                {
                    IErpOrganisation organisationCasted = item.As <IErpOrganisation>();
                    if ((organisationCasted != null))
                    {
                        this._parent.Organisation = organisationCasted;
                        return;
                    }
                }
                IWork worksCasted = item.As <IWork>();

                if ((worksCasted != null))
                {
                    this._parent.Works.Add(worksCasted);
                }
                if ((this._parent.ErpQuoteLineItem == null))
                {
                    IErpQuoteLineItem erpQuoteLineItemCasted = item.As <IErpQuoteLineItem>();
                    if ((erpQuoteLineItemCasted != null))
                    {
                        this._parent.ErpQuoteLineItem = erpQuoteLineItemCasted;
                        return;
                    }
                }
                IProject projectsCasted = item.As <IProject>();

                if ((projectsCasted != null))
                {
                    this._parent.Projects.Add(projectsCasted);
                }
            }
示例#9
0
            /// <summary>
            /// Removes the given item from the collection
            /// </summary>
            /// <returns>True, if the item was removed, otherwise False</returns>
            /// <param name="item">The item that should be removed</param>
            public override bool Remove(IModelElement item)
            {
                if ((this._parent.Organisation == item))
                {
                    this._parent.Organisation = null;
                    return(true);
                }
                IWork workItem = item.As <IWork>();

                if (((workItem != null) &&
                     this._parent.Works.Remove(workItem)))
                {
                    return(true);
                }
                if ((this._parent.ErpQuoteLineItem == item))
                {
                    this._parent.ErpQuoteLineItem = null;
                    return(true);
                }
                IProject projectItem = item.As <IProject>();

                if (((projectItem != null) &&
                     this._parent.Projects.Remove(projectItem)))
                {
                    return(true);
                }
                return(false);
            }
示例#10
0
        public static int SendWork(this IEnumerable <Socket> sockets, IWork work)
        {
            using (var stream = new MemoryStream())
            {
                var lengthWriter = new BinaryWriter(stream);
                lengthWriter.Write(0);

                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, work);

                lengthWriter.Seek(0, SeekOrigin.Begin);
                lengthWriter.Write((int)(stream.Length - sizeof(int)));

                var bytes = stream.ToArray();
                var tasks = sockets.Select(socket => socket.SendAsync(bytes)).ToList();
                try
                {
                    Task.WaitAll(tasks.Cast <Task>().ToArray());
                }
                catch (Exception)
                {
                    return(tasks.Count(e => e.IsCompleted));
                }
                return(tasks.Count());
            }
        }
示例#11
0
        private void DoWork(IWork work)
        {
            try
            {
                this.NotifyObservers(work, work.GetResult());
            }
            catch (Exception exception)
            {
                Exception e = exception;
                switch (this.ExceptionHandling)
                {
                case ExceptionHandlingAction.DefaultBehaviour:
                {
                    throw;
                }

                case ExceptionHandlingAction.CallEventHandler:
                {
                    this.OnException(e);
                    break;
                }

                case ExceptionHandlingAction.CallEventHandlerAndLeakException:
                {
                    this.OnException(e);
                    throw;
                }
                }
            }
        }
示例#12
0
        static void Main(string[] args)
        {
            //Interfacelerin kullanım şekilleri
            CustomerManager customerManger = new CustomerManager();

            //customerManger.Add(new SQLiteDal());
            //customerManger.Delete(new OracleDal());

            ICustomerDal[] customerDals = new ICustomerDal[]
            {
                new SQLiteDal(),
                new OracleDal()
            };

            foreach (ICustomerDal customerDal in customerDals)
            {
                customerDal.Add();
                customerDal.Delete();
                customerDal.Update();
            }

            //Çoklu implementasyon örneği için MultiImplementation.cs bakınız...
            //Devamı

            IWork[] workersArray = new IWork[]
            {
                new Manager(),
                new Worker(),
                new Robot()
            };

            IEat[] eatArray = new IEat[]
            {
                new Manager(),
                new Worker()
            };

            ISalary[] salaryArray = new ISalary[]
            {
                new Manager(),
                new Worker()
            };

            foreach (IWork worker in workersArray)
            {
                worker.Work();
            }

            foreach (IEat eater in eatArray)
            {
                eater.Eat();
            }

            foreach (ISalary salaryGetter in salaryArray)
            {
                salaryGetter.Salary();
            }

            Console.Read();
        }
示例#13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="work">work的创建和销毁由外界处理</param>
        /// <param name="run"></param>
        /// <returns></returns>
        public void AddWork(IWork work, bool run = false)
        {
            if (work != null && !allWorks.Contains(work))
            {
                allWorks.Add(work);

                if (run)
                {
                    if (runningCount < runningWorks.Count)
                    {
                        runningWorks[runningCount++] = work;
                    }
                    else
                    {
                        runningWorks.Add(work);
                        runningCount++;
                    }

                    work.Start();
                    (work as ITick).Tick(0);                    //有些需要立即生效
                    if (work.IsFinished())
                    {
                        allWorks.Remove(work);
                        runningWorks.Remove(work);
                        runningCount--;
                    }
                }
            }
        }
        protected void SetUp()
        {
            Test test = new Test("Default", 0, 0, 0, 0, 0);

            Configuration.Initialize(test);

            _workorder = Substitute.For <IWork>();
            _workorder.CurrentOpType.Returns(Op.OpTypes.DrillOpType1);
            _workorder.CurrentOpSetupTime.Returns(0);
            _workorder.CurrentOpEstTimeToComplete.Returns(1);
            _workorder.Id.Returns(1);

            ISchedulePlants ps = Substitute.For <ISchedulePlants>();

            ps.ValidateWoForMachines(Arg.Any <int>(), Arg.Any <string>()).Returns(x => x[0]);
            _plant = Substitute.For <IPlant>();
            _plant.PlantScheduler.Returns(ps);

            _bigData = Substitute.For <IHandleBigData>();
            _bigData.IsBreakdown(Arg.Any <string>(), Arg.Any <DayTime>()).Returns(x => x[1]);
            _bigData.IsNonConformance(Arg.Any <string>()).Returns(false);

            _mes     = Substitute.For <IMes>();
            _dayTime = new DayTime();
            _subject = new Workcenter("TestWC", Machine.Types.BigDrill);
            _subject.SetMes(_mes);

            _subject.AddPlant(_plant);
            _subject.AddBigData(_bigData);
        }
示例#15
0
            /// <summary>
            /// Adds the given element to the collection
            /// </summary>
            /// <param name="item">The item to add</param>
            public override void Add(IModelElement item)
            {
                IWorkTask workTasksCasted = item.As <IWorkTask>();

                if ((workTasksCasted != null))
                {
                    this._parent.WorkTasks.Add(workTasksCasted);
                }
                if ((this._parent.Status == null))
                {
                    IStatus statusCasted = item.As <IStatus>();
                    if ((statusCasted != null))
                    {
                        this._parent.Status = statusCasted;
                        return;
                    }
                }
                if ((this._parent.Work == null))
                {
                    IWork workCasted = item.As <IWork>();
                    if ((workCasted != null))
                    {
                        this._parent.Work = workCasted;
                        return;
                    }
                }
            }
示例#16
0
 private static void AtWorkStation(IWork w)
 {
     Console.WriteLine("AtWorkStation");
     Console.WriteLine();
     w.StartWork();
     w.StopWork();
 }
示例#17
0
 public bool Add(IWork work, QueuePriority queuePriority)
 {
     if (!_run)
     {
         return(false);
     }
     if (_startInfo.DelayedInit)
     {
         _startInfo.DelayedInit = false;
         Init();
     }
     if (work == null)
     {
         throw new ArgumentNullException("work", "cannot be null");
     }
     if (work.State != WorkState.INIT)
     {
         throw new InvalidOperationException(String.Format("WorkState must be {0}", WorkState.INIT));
     }
     if (!_run)
     {
         throw new InvalidOperationException("Threadpool is already (being) stopped");
     }
     work.State = WorkState.INQUEUE;
     _workQueue.Add(work, queuePriority);
     CheckThreadIncrementRequired();
     return(true);
 }
示例#18
0
            /// <summary>
            /// Adds the given element to the collection
            /// </summary>
            /// <param name="item">The item to add</param>
            public override void Add(IModelElement item)
            {
                IProject projectsCasted = item.As <IProject>();

                if ((projectsCasted != null))
                {
                    this._parent.Projects.Add(projectsCasted);
                }
                IWorkCostDetail workCostDetailsCasted = item.As <IWorkCostDetail>();

                if ((workCostDetailsCasted != null))
                {
                    this._parent.WorkCostDetails.Add(workCostDetailsCasted);
                }
                IErpTimeEntry erpTimeEntriesCasted = item.As <IErpTimeEntry>();

                if ((erpTimeEntriesCasted != null))
                {
                    this._parent.ErpTimeEntries.Add(erpTimeEntriesCasted);
                }
                IWork worksCasted = item.As <IWork>();

                if ((worksCasted != null))
                {
                    this._parent.Works.Add(worksCasted);
                }
            }
示例#19
0
        public IWork Ship(int wo_id)
        {
            IWork wo = ShippingBuffer.Remove(wo_id);

            _mes.Ship(wo_id);
            return(wo);
        }
 public CategoriesController(ICategoryRepository repo, IMapper mapper, IBookRepository bookRepo, IWork work)
 {
     _repo     = repo;
     _mapper   = mapper;
     _bookRepo = bookRepo;
     _work     = work;
 }
示例#21
0
 /// <summary>
 /// Called by workers when the job queue is empty.
 /// </summary>
 internal void ReportInactive()
 {
     if (Interlocked.Decrement(ref activeThreads) <= 0)
     {
         IWork next = null;
         currentJob?.TriggerComplete();
         lock (workQueue) {
             // Remove the old head, and check for a new one
             int n = workQueue.Count;
             if (n > 0)
             {
                 workQueue.Dequeue();
             }
             if (n > 1)
             {
                 next = workQueue.Peek();
             }
             else
             {
                 // Avoid concurrent mod exception if another task starts up afterwards
                 foreach (var thread in threads)
                 {
                     thread.PrintExceptions();
                 }
             }
             currentJob = null;
         }
         if (next != null)
         {
             AdvanceNext(next);
         }
     }
 }
        private void GameMain_gameUpdateEvent(GameTime gameTime)
        {
            if (_works.Count > 0)
            {
                lock (_syncWorks)
                {
                    TimeSpan totalDelta    = TimeSpan.Zero;
                    int      execWorkCount = 0;
                    int      totalWorks    = _works.Count;

                    for (int i = 0; i < _works.Count;)
                    {
                        var t1 = DateTime.Now;

                        IWork work = _works[i];
                        _works.RemoveAt(i);

                        work.run(gameTime);

                        var delta = DateTime.Now - t1;
                        totalDelta += delta;
                        if (totalDelta.TotalSeconds > 0.01f)
                        {
                            break;
                        }
                        execWorkCount++;
                    }

                    if (execWorkCount > 0)
                    {
                        // Console.WriteLine("execWork={0}/{1} totalDelta={2}", execWorkCount, totalWorks, totalDelta);
                    }
                }
            }
        }
示例#23
0
        /// <summary> Create <see cref="ITaskWrapper{TArgument}" /> for given asyncWork </summary>
        /// <param name="work"> Work instance </param>
        /// <param name="attemptsCount"> Retry on fail attempts count </param>
        /// <param name="cancellation"> Work cancellation token </param>
        /// <returns> Wrapper and asyncWork completion task </returns>
        public static (ITaskWrapper <object?> Work, Task Task) CreateWorkWrapper(IWork work, int attemptsCount  = 1,
                                                                                 CancellationToken cancellation = default)
        {
            var wrapper = new WorkWrapper(work ?? throw new ArgumentNullException(nameof(work)), Math.Max(1, attemptsCount), cancellation);

            return(wrapper, wrapper.WorkTask);
        }
示例#24
0
        static void Main(string[] args)
        {
            IWork[] workers = new IWork[3]
            {
                new Manager(),
                new Worker(),
                new Robot()
            };

            foreach (var worker in workers)
            {
                worker.Work();
            }



            IEat[] eats = new IEat[2]
            {
                new Worker(),
                new Manager()
            };

            foreach (var eat in eats)
            {
                eat.Eat();
            }
        }
示例#25
0
        public void Add(IWork workorder)
        {
            var wc = Workcenters.First(x => x.ReceivesType(workorder.CurrentOpType));

            Mes.AddWorkorder(wc.Name, workorder);
            wc.AddToQueue(workorder);
        }
        protected static void OnWorkOverwrite(object sender, WorkOverwriteEventArgs e)
        {
            IWork work = (sender as IWork);

            if (GetDefaultOverwriteMode(work.ID) != OverwriteMode.Ask)
            {
                e.Overwrite = GetDefaultOverwriteMode(work.ID);
            }
            if (work.Aborted)
            {
                e.Overwrite = OverwriteMode.KeepOriginal;
            }

            if (!GetIsMuted((sender as IWork).ID))
            {
                if (WorkOverwrite != null)
                {
                    WorkOverwrite(sender, e);
                    if (e.ApplyToAll)
                    {
                        SetDefaultOverwriteMode(work.ID, e.Overwrite);
                    }
                }
            }
        }
示例#27
0
 public bool RemoveWork(IWork work)
 {
     foreach (string action in work.Action)
     {
         if (this.work.ContainsKey(action))
         {
             if (this.work[action].Count > 1)
             {
                 foreach (string upon in work.Upon)
                 {
                     this.work[action].Remove(upon);
                 }
                 if (this.work[action].Count == 0)
                 {
                     this.work.Remove(action);
                 }
             }
             else
             {
                 this.work.Remove(action);
             }
             return(true);
         }
     }
     return(false);
 }
示例#28
0
 public MainForm()
 {
     InitializeComponent();
     this.rand = new Random();
     this.work = new PrimeResolutionWork(this.rand);
     this.helper = new ClientHelper(this.rand, this.lbEventDiary, this.work);
 }
示例#29
0
        public IWork BootLoad()
        {
            if (state == ManagerState.INIT)
            {
                state = ManagerState.BOOT_LOADING;
                var loaders = TempList <IWork> .Alloc();

                var loader = DoLoad();
                if (loader != null)
                {
                    loaders.Add(loader);
                }

                foreach (var module in modules.Values)
                {
                    var work = module.Load();
                    if (work != null)
                    {
                        loaders.Add(work);
                    }
                }
                if (loaders.Count > 0)
                {
                    return(bootLoader = new ParallelWork("", loaders));
                }
            }

            return(null);
        }
示例#30
0
文件: ThreadPool.cs 项目: rc183/igf
        /// <summary>
        /// Executes the given work items potentially in parallel with each other.
        /// This method will block until all work is completed.
        /// </summary>
        /// <param name="a">Work to execute.</param>
        /// <param name="b">Work to execute.</param>
        public void Do(IWork a, IWork b)
        {
            Task task = Start(b);

            a.DoWork();
            task.Wait();
        }
示例#31
0
 protected virtual void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     while (MainList.Count > 0)
     {
         IWork work = MainList.First.Value;
         if (!work.Initialize())
         {
             work.OnFailed();
             RunOnFailed();
             return;
         }
         if (!work.Execute())
         {
             work.OnFailed();
             RunOnFailed();
             return;
         }
         work.OnCompleted();
         MainList.RemoveFirst();
     }
     if (MainList.Count == 0)
     {
         RunOnCompleted();
     }
 }
示例#32
0
            /// <summary>
            /// Removes the given item from the collection
            /// </summary>
            /// <returns>True, if the item was removed, otherwise False</returns>
            /// <param name="item">The item that should be removed</param>
            public override bool Remove(IModelElement item)
            {
                IProject projectItem = item.As <IProject>();

                if (((projectItem != null) &&
                     this._parent.Projects.Remove(projectItem)))
                {
                    return(true);
                }
                IWorkCostDetail workCostDetailItem = item.As <IWorkCostDetail>();

                if (((workCostDetailItem != null) &&
                     this._parent.WorkCostDetails.Remove(workCostDetailItem)))
                {
                    return(true);
                }
                IErpTimeEntry erpTimeEntryItem = item.As <IErpTimeEntry>();

                if (((erpTimeEntryItem != null) &&
                     this._parent.ErpTimeEntries.Remove(erpTimeEntryItem)))
                {
                    return(true);
                }
                IWork workItem = item.As <IWork>();

                if (((workItem != null) &&
                     this._parent.Works.Remove(workItem)))
                {
                    return(true);
                }
                return(false);
            }
示例#33
0
        public void Dequeue_WhenHas1_ReturnsIt()
        {
            _subject.Enqueue(wo1);
            IWork wo = _subject.Dequeue();

            Assert.AreEqual(wo.Id, wo1.Id);
        }
        /// <summary>
        ///  Enqueues the task.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <param name="skipIfAny">Skip task execution if any other task are queued</param>
        private async void Post(IWork task)
        {
            if (disposed)
            {
                throw new InvalidOperationException("Worker is already disposed");
            }

            await semaphore.WaitAsync();

            await Task.Run(() =>
            {
                try
                {
                    lock (_locker)
                    {
                        _workQueue.Enqueue(task);
                        Monitor.PulseAll(_locker);
                    }
                }
                finally
                {
                    semaphore.Release();
                }
            });
        }
示例#35
0
        public IWork Work(DayTime dayTime, IHandleBigData bigData, string name)
        {
            if (CurrentWo == null)
            {
                if (Buffer.Count > 0)
                {
                    CurrentWo             = Buffer.Dequeue();
                    CurrentInspectionTime = _inspectionTime;
                }
                return(null);
            }

            IWork answer = null;

            CurrentInspectionTime--;
            if (CurrentInspectionTime == 0)
            {
                answer    = CurrentWo;
                CurrentWo = null;

                answer.NonConformance = bigData.IsNonConformance(name);
                if (!answer.NonConformance)
                {
                    answer.SetNextOp();
                }
            }

            return(answer);
        }
示例#36
0
 public void Reset()
 {
     _work     = null;
     _timedout = false;
     _signaled = false;
     _waitHandle.Reset();
 }
 public NeedSomeOneToDoWork(IWork worker)
 {
     if (worker == null)
     {
         throw new ArgumentNullException(nameof(worker));
     }
     _worker = worker;
 }
 private void HandleEnded(IWork sender, WorkEventArgs e)
 {
     if (_workUnits.Any(w => !w.Equals(sender) && !w.HasEnded))
     {
         return;
     }
     EndTransaction(_workUnits.All(w => w.IsComplete));
 }
示例#39
0
 public Work(WorkType type, IWork parent, IArtist artist, string name, short year, uint number)
 {
     this.type = type;
     this.parent = parent;
     this.artist = artist;
     this.name = name ?? string.Empty;
     this.year = year;
     this.number = number;
 }
示例#40
0
        public void AddWork(IWork work)
        {
            if (work == null)
                throw new ArgumentNullException("work");

            if (works.Contains(work))
                return;

            works.Add(work);
        }
        public void EndWorking()
        {
            var currentProgressService = CurrentWork;
            currentProgressService.EndWork();

            _lastWork = _worksStack.Pop();

            if (!_worksStack.Any())
                IsWorrking = false;
        }
示例#42
0
        public void RemoveWork(IWork work)
        {
            if (work == null)
                throw new ArgumentNullException("work");

            if (!works.Contains(work))
                return;

            works.Remove(work);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="WorkFailedProcessingEventArgs"/> class.
        /// </summary>
        /// 
        /// <param name="work">
        /// The item of <see cref="IWork"/> that has failed.
        /// </param>
        /// 
        /// <param name="message">
        /// A message that indicates what has failed.
        /// </param>
        /// 
        /// <exception cref="ArgumentException">
        /// If <paramref name="work"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ArgumentException">
        /// If <paramref name="message"/> is null, blank or whitespace.
        /// </exception>
        public WorkFailedProcessingEventArgs(IWork work, string message)
        {
            if (work == null)
                throw new ArgumentException("Argument: 'work' may not be null.");

            if (string.IsNullOrWhiteSpace(message))
                throw new ArgumentException("Argument: 'message' may not be null, blank or whitespace.");

            this.Message = message;
            this.Work = work;
        }
示例#44
0
 /// <summary>
 /// Registers/Adds work to the <see cref="CrawlerWorkSource"/>.
 /// </summary>
 /// <param name="work"><see cref="ICrawlerWork"/></param>
 public void RegisterWork(IWork work)
 {
     if (work.IsReadyToStart())
     {
         availableWork.Enqueue(work);
     }
     else
     {
         workSourceScheduler.ScheduleWork(work);
     }
 }
示例#45
0
        public void Log(IWork work, logType type, string message)
        {
            lock (_logList)
            {
                if (_lastLog.Type != type || _lastLog.Message != message)
                    _logList.Add(_lastLog = new logLine(type, message));

                if (!String.IsNullOrEmpty(_fileName) && (type == logType.error || type == logType.success))
                    using (StreamWriter sw = new StreamWriter(File.OpenWrite(_fileName)))
                        foreach (var line in _logList)
                            sw.WriteLine(String.Format("[{0}] {1} - {2}", line.Time, line.Type.ToString(), line.Message));
            }
        }
示例#46
0
        public void Publish(IWork work, string routingKey = null, IBasicProperties properties = null)
        {
            if (work == null)
                throw new ArgumentNullException(nameof(work));

            if (string.IsNullOrWhiteSpace(routingKey))
                throw new ArgumentNullException(nameof(routingKey));

            if (properties == null)
            {
                properties = this.Channel.CreateBasicProperties();

                //properties.AppId = string.Empty;
                //properties.ClusterId = string.Empty;
                //properties.ContentEncoding = string.Empty;
                //properties.ContentType = "application/json"; // Set by the Message Serializer
                //properties.CorrelationId = string.Empty;
                properties.DeliveryMode = Constants.Persistent;
                //properties.Expiration = string.Empty;
                //properties.MessageId = string.Empty;
                //properties.Priority = 0;
                //properties.ReplyTo = string.Empty;
                //properties.Type = msg.GetType().Name; // Set by the Message Serializer, use this field to store the type of object encoded in the Body. Allows for a factory deserializer to easily determine what to return
                //properties.UserId = string.Empty;
            }

            if (!this.Channel.IsOpen)
                throw new InvalidOperationException("Channel is not open");

            var bytes = WorkSerializer.Serialize(work);
            properties.ContentEncoding = WorkSerializer.ContentEncoding;
            properties.ContentType = WorkSerializer.ContentType;
            properties.Type = work.GetType().FullName;

            var WorkExchange = Constants.WorkExchangeSettings;
            this.Channel.ExchangeDeclare(WorkExchange.Name, WorkExchange.ExchangeType, WorkExchange.Durable, WorkExchange.AutoDelete, WorkExchange.Arguments);
            this.Channel.BasicPublish(WorkExchange.Name, routingKey, properties, bytes);
        }
示例#47
0
 public void Add(IWork work, QueuePriority priority)
 {
   lock (_queueMutex)
   {
     bool mustQueue = true;
     while (_workWaiters.Count > 0)
     {
       WorkWaiter waiter = _workWaiters[0];
       _workWaiters.Remove(waiter);
       if (waiter.Signal(work))
       {
         mustQueue = false;
         break;
       }
     }
     if (mustQueue)
     {
       Queue<IWork> queue = GetQueue(priority);
       queue.Enqueue(work);
       _queueItemCount++;
     }
   }
 }
        /// <summary>
        /// Enqueues the specified work.
        /// </summary>
        /// <param name="work">The work.</param>
        /// <returns><value>true</value> if the work was enqueued, else <value>false</value>.</returns>
        /// <exception cref="ArgumentException">
        /// If <paramref name="work"/> is null.
        /// </exception>
        public void Enqueue(IWork work)
        {
            if (work == null)
                throw new ArgumentException("Argument: 'work' must not be null.");

            lock (this.queueLocker)
            {
                this.queue.Enqueue(work);
                Monitor.Pulse(this.queueLocker);
            }
        }
示例#49
0
        private void WorkItemHandler(IBasicProperties props, IWork iWork)
        {
            var work = iWork as SampleWorkItem;
            if (work == null)
                throw new Exception($"Don't know how to work on '{iWork.GetType().FullName}' items");

            this.InternalState = InternalStateEnum.Busy;

            var currentStatus = new ServiceComponentStatus() { Process = this.Process, ServiceComponent = this.GetType().Name, Status = "Working", SubStatus = "Starting" };
            this.PublishEvent(currentStatus);

            var workItemType = work.ItemType;
            var workItemId = work.ItemId;
            var workDelay = work.WorkDelay;

            currentStatus.SubStatus = "Executing";
            this.PublishEvent(currentStatus);

            Thread.Sleep(workDelay);

            currentStatus.SubStatus = "Completing";
            this.PublishEvent(currentStatus);

            this.InternalState = InternalStateEnum.Idle;
            this.PublishEvent("Idle");
        }
示例#50
0
		public WorkerThread(IWork work, string name) : this(new ThreadStart(work.Start), name)
		{
		}
示例#51
0
 public void Reset()
 {
   _work = null;
   _timedout = false;
   _signaled = false;
   _waitHandle.Reset();
 }
示例#52
0
 public bool Add(IWork work)
 {
   return Add(work, QueuePriority.Normal);
 }
示例#53
0
 public bool Add(IWork work, QueuePriority queuePriority)
 {
   if (!_run)
     return false;
   if (_startInfo.DelayedInit)
   {
     _startInfo.DelayedInit = false;
     Init();
   }
   if (work == null)
     throw new ArgumentNullException("work", "cannot be null");
   if (work.State != WorkState.INIT)
     throw new InvalidOperationException(String.Format("WorkState must be {0}", WorkState.INIT));
   if (!_run)
     throw new InvalidOperationException("Threadpool is already (being) stopped");
   work.State = WorkState.INQUEUE;
   _workQueue.Add(work, queuePriority);
   CheckThreadIncrementRequired();
   return true;
 }
示例#54
0
 /// <summary>
 /// Adds work to the pool's <see cref="CrawlerWorkSource"/> 
 /// </summary>
 /// <param name="job"></param>
 public void AddWork(IWork job)
 {
     workSource.RegisterWork(job);
     jobsInSource++;
 }
示例#55
0
 public void Add(IWork work)
 {
   Add(work, QueuePriority.Normal);
 }
        private void HandleFailedWork(IWork workToBeProcessed, string message)
        {
            lock (this.queueLocker)
            {
                this.failed.Add(workToBeProcessed);

                var args = new WorkFailedProcessingEventArgs(workToBeProcessed, message);
                this.OnWorkFailed(args);
            }
        }
        private void SaveWork(IBatch<IWork> batch, IWork work)
        {
            batch.Save(work);

            foreach (var child in work.Children)
            {
                SaveWork(batch, child);
            }
        }
示例#58
0
 public bool Signal(IWork work)
 {
   lock (this)
   {
     if (!_timedout)
     {
       _work = work;
       _signaled = true;
       _waitHandle.Set();
       return true;
     }
   }
   return false;
 }
示例#59
0
        public void ScheduleWork(IWork work)
        {
            unmanagedPendingWork.Enqueue(work);

            WakeUpTheManager();
        }
示例#60
0
 /// <summary>
 /// Schedule saving of all settings in the near future
 /// </summary>
 public static void Save()
 {
   IThreadPool tp = GlobalServiceProvider.Get<IThreadPool>();
   if (_delaySave == null)
   {
     _delaySave = tp.Add(LazySave, "Wait for saving SkinSettings");
   } 
   else if (_delaySave.State != WorkState.INPROGRESS && _delaySave.State != WorkState.INQUEUE)
   {
     _delaySave = tp.Add(LazySave,"Wait for saving SkinSettings");
   }
   
 }