BackgroundJobExecutor.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. namespace NRKernal
  10. {
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Diagnostics.CodeAnalysis;
  14. using System.Threading;
  15. /// <summary> A background job executor. </summary>
  16. [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented",
  17. Justification = "Internal")]
  18. public class BackgroundJobExecutor
  19. {
  20. /// <summary> The event. </summary>
  21. private AutoResetEvent m_Event = new AutoResetEvent(false);
  22. /// <summary> Queue of jobs. </summary>
  23. private Queue<Action> m_JobsQueue = new Queue<Action>();
  24. /// <summary> The thread. </summary>
  25. private Thread m_Thread;
  26. /// <summary> True to running. </summary>
  27. private bool m_Running = false;
  28. /// <summary> Default constructor. </summary>
  29. public BackgroundJobExecutor()
  30. {
  31. m_Thread = new Thread(Run);
  32. m_Thread.Start();
  33. }
  34. /// <summary> Gets the number of pending jobs. </summary>
  35. /// <value> The number of pending jobs. </value>
  36. public int PendingJobsCount
  37. {
  38. get
  39. {
  40. lock (m_JobsQueue)
  41. {
  42. return m_JobsQueue.Count + (m_Running ? 1 : 0);
  43. }
  44. }
  45. }
  46. /// <summary> Pushes a job. </summary>
  47. /// <param name="job"> The job.</param>
  48. public void PushJob(Action job)
  49. {
  50. lock (m_JobsQueue)
  51. {
  52. m_JobsQueue.Enqueue(job);
  53. }
  54. m_Event.Set();
  55. }
  56. /// <summary> Removes all pending jobs. </summary>
  57. public void RemoveAllPendingJobs()
  58. {
  59. lock (m_JobsQueue)
  60. {
  61. m_JobsQueue.Clear();
  62. }
  63. }
  64. /// <summary> Runs this object. </summary>
  65. private void Run()
  66. {
  67. while (true)
  68. {
  69. if (PendingJobsCount == 0)
  70. {
  71. m_Event.WaitOne();
  72. }
  73. Action job = null;
  74. lock (m_JobsQueue)
  75. {
  76. if (m_JobsQueue.Count == 0)
  77. {
  78. continue;
  79. }
  80. job = m_JobsQueue.Dequeue();
  81. m_Running = true;
  82. }
  83. job();
  84. lock (m_JobsQueue)
  85. {
  86. m_Running = false;
  87. }
  88. }
  89. }
  90. }
  91. }