ObjectJobEngine.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. // A pool of jobs or workitems with same method (callback) but diferent argument (as object) to run in main threadpool
  28. // can have up to m_concurrency number of execution threads
  29. // it will hold each thread up to m_threadsHoldtime ms waiting for more work, before releasing it back to the pool.
  30. using System;
  31. using System.Collections.Concurrent;
  32. using System.Reflection;
  33. using System.Threading;
  34. using log4net;
  35. namespace OpenSim.Framework
  36. {
  37. public class ObjectJobEngine : IDisposable
  38. {
  39. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  40. private readonly object m_mainLock = new object();
  41. private readonly string m_name;
  42. private readonly int m_threadsHoldtime;
  43. private readonly int m_concurrency = 1;
  44. private BlockingCollection<object> m_jobQueue;
  45. private CancellationTokenSource m_cancelSource;
  46. private WaitCallback m_callback;
  47. private int m_numberThreads = 0;
  48. private bool m_isRunning;
  49. public ObjectJobEngine(WaitCallback callback, string name, int threadsHoldtime = 1000, int concurrency = 1)
  50. {
  51. m_name = name;
  52. m_threadsHoldtime = threadsHoldtime;
  53. if (concurrency < 1)
  54. m_concurrency = 1;
  55. else
  56. m_concurrency = concurrency;
  57. if (callback != null)
  58. {
  59. m_callback = callback;
  60. m_jobQueue = new BlockingCollection<object>();
  61. m_cancelSource = new CancellationTokenSource();
  62. m_isRunning = true;
  63. }
  64. }
  65. ~ObjectJobEngine()
  66. {
  67. Dispose(false);
  68. }
  69. public void Dispose()
  70. {
  71. Dispose(true);
  72. GC.SuppressFinalize(this);
  73. }
  74. private void Dispose(bool disposing)
  75. {
  76. lock(m_mainLock)
  77. {
  78. if (!m_isRunning)
  79. return;
  80. m_isRunning = false;
  81. m_cancelSource.Cancel();
  82. }
  83. if (m_numberThreads > 0)
  84. {
  85. int cntr = 100;
  86. while (m_numberThreads > 0 && --cntr > 0)
  87. Thread.Yield();
  88. }
  89. if (m_jobQueue != null)
  90. {
  91. m_jobQueue.Dispose();
  92. m_jobQueue = null;
  93. }
  94. if (m_cancelSource != null)
  95. {
  96. m_cancelSource.Dispose();
  97. m_cancelSource = null;
  98. }
  99. m_callback = null;
  100. }
  101. /// <summary>
  102. /// Number of jobs waiting to be processed.
  103. /// </summary>
  104. public int Count { get { return m_jobQueue == null ? 0 : m_jobQueue.Count; } }
  105. public void Cancel()
  106. {
  107. if (!m_isRunning || m_jobQueue == null || m_jobQueue.Count == 0)
  108. return;
  109. try
  110. {
  111. while(m_jobQueue.TryTake(out _));
  112. m_cancelSource.Cancel();
  113. }
  114. catch { }
  115. }
  116. /// <summary>
  117. /// Queue the job for processing.
  118. /// </summary>
  119. /// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
  120. /// <param name="job">The job</param>
  121. /// </param>
  122. public bool Enqueue(object o)
  123. {
  124. if (!m_isRunning)
  125. return false;
  126. lock (m_mainLock)
  127. {
  128. m_jobQueue?.Add(o);
  129. if (m_numberThreads < m_concurrency && m_numberThreads < m_jobQueue.Count)
  130. {
  131. Util.FireAndForget(ProcessRequests, null, m_name, false);
  132. ++m_numberThreads;
  133. }
  134. }
  135. return true;
  136. }
  137. private void ProcessRequests(object o)
  138. {
  139. object obj;
  140. while (m_isRunning)
  141. {
  142. try
  143. {
  144. if(!m_jobQueue.TryTake(out obj, m_threadsHoldtime, m_cancelSource.Token))
  145. {
  146. lock (m_mainLock)
  147. {
  148. if (m_jobQueue.Count > 0)
  149. continue;
  150. --m_numberThreads;
  151. return;
  152. }
  153. }
  154. }
  155. catch
  156. {
  157. break;
  158. }
  159. if(!m_isRunning || m_callback == null)
  160. break;
  161. try
  162. {
  163. m_callback.Invoke(obj);
  164. obj = null;
  165. }
  166. catch (Exception e)
  167. {
  168. m_log.ErrorFormat("[ObjectJob {0}]: Job failed, continuing. Exception {1}", m_name, e);
  169. }
  170. }
  171. lock (m_mainLock)
  172. --m_numberThreads;
  173. }
  174. }
  175. }