/**************************************************************************** * Copyright 2019 Nreal Techonology Limited. All rights reserved. * * This file is part of NRSDK. * * https://www.nreal.ai/ * *****************************************************************************/ namespace NRKernal { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; /// A background job executor. [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Internal")] public class BackgroundJobExecutor { /// The event. private AutoResetEvent m_Event = new AutoResetEvent(false); /// Queue of jobs. private Queue m_JobsQueue = new Queue(); /// The thread. private Thread m_Thread; /// True to running. private bool m_Running = false; /// Default constructor. public BackgroundJobExecutor() { m_Thread = new Thread(Run); m_Thread.Start(); } /// Gets the number of pending jobs. /// The number of pending jobs. public int PendingJobsCount { get { lock (m_JobsQueue) { return m_JobsQueue.Count + (m_Running ? 1 : 0); } } } /// Pushes a job. /// The job. public void PushJob(Action job) { lock (m_JobsQueue) { m_JobsQueue.Enqueue(job); } m_Event.Set(); } /// Removes all pending jobs. public void RemoveAllPendingJobs() { lock (m_JobsQueue) { m_JobsQueue.Clear(); } } /// Runs this object. private void Run() { while (true) { if (PendingJobsCount == 0) { m_Event.WaitOne(); } Action job = null; lock (m_JobsQueue) { if (m_JobsQueue.Count == 0) { continue; } job = m_JobsQueue.Dequeue(); m_Running = true; } job(); lock (m_JobsQueue) { m_Running = false; } } } } }