ManagedThreadPoolcs.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Collections;
  7. namespace MyTest
  8. {
  9. class ManagedThreadPoolcs
  10. {
  11. public class Semaphore
  12. {
  13. #region Member Variables
  14. /// <summary>The number of units alloted by this semaphore.</summary>
  15. private int _count;
  16. /// <summary>Lock for the semaphore.</summary>
  17. private object _semLock = new object();
  18. #endregion
  19. #region Construction
  20. /// <summary> Initialize the semaphore as a binary semaphore.</summary>
  21. public Semaphore()
  22. : this(1)
  23. {
  24. }
  25. /// <summary> Initialize the semaphore as a counting semaphore.</summary>
  26. /// <param name="count">Initial number of threads that can take out units from this semaphore.</param>
  27. /// <exception cref="ArgumentException">Throws if the count argument is less than 0.</exception>
  28. public Semaphore(int count)
  29. {
  30. if (count < 0) throw new ArgumentException("Semaphore must have a count of at least 0.", "count");
  31. _count = count;
  32. }
  33. #endregion
  34. #region Synchronization Operations
  35. /// <summary>V the semaphore (add 1 unit to it).</summary>
  36. public void AddOne() { V(); }
  37. /// <summary>P the semaphore (take out 1 unit from it).</summary>
  38. public void WaitOne() { P(); }
  39. /// <summary>P the semaphore (take out 1 unit from it).</summary>
  40. public void P()
  41. {
  42. // Lock so we can work in peace. This works because lock is actually
  43. // built around Monitor.
  44. lock (_semLock)
  45. {
  46. // Wait until a unit becomes available. We need to wait
  47. // in a loop in case someone else wakes up before us. This could
  48. // happen if the Monitor.Pulse statements were changed to Monitor.PulseAll
  49. // statements in order to introduce some randomness into the order
  50. // in which threads are woken.
  51. while (_count <= 0) Monitor.Wait(_semLock, Timeout.Infinite);
  52. _count--;
  53. }
  54. }
  55. /// <summary>V the semaphore (add 1 unit to it).</summary>
  56. public void V()
  57. {
  58. // Lock so we can work in peace. This works because lock is actually
  59. // built around Monitor.
  60. lock (_semLock)
  61. {
  62. // Release our hold on the unit of control. Then tell everyone
  63. // waiting on this object that there is a unit available.
  64. _count++;
  65. Monitor.Pulse(_semLock);
  66. }
  67. }
  68. /// <summary>Resets the semaphore to the specified count. Should be used cautiously.</summary>
  69. public void Reset(int count)
  70. {
  71. lock (_semLock) { _count = count; }
  72. }
  73. #endregion
  74. }
  75. /// <summary>Managed thread pool.</summary>
  76. public class ManagedThreadPool
  77. {
  78. #region Constants
  79. /// <summary>Maximum number of threads the thread pool has at its disposal.</summary>
  80. private const int _maxWorkerThreads = 80;
  81. #endregion
  82. #region Member Variables
  83. /// <summary>Queue of all the callbacks waiting to be executed.</summary>
  84. private static Queue _waitingCallbacks;
  85. /// <summary>
  86. /// Used to signal that a worker thread is needed for processing. Note that multiple
  87. /// threads may be needed simultaneously and as such we use a semaphore instead of
  88. /// an auto reset event.
  89. /// </summary>
  90. private static Semaphore _workerThreadNeeded;
  91. /// <summary>List of all worker threads at the disposal of the thread pool.</summary>
  92. private static ArrayList _workerThreads;
  93. /// <summary>Number of threads currently active.</summary>
  94. private static int _inUseThreads;
  95. /// <summary>Lockable object for the pool.</summary>
  96. private static object _poolLock = new object();
  97. #endregion
  98. #region Construction and Finalization
  99. /// <summary>Initialize the thread pool.</summary>
  100. static ManagedThreadPool() { Initialize(); }
  101. /// <summary>Initializes the thread pool.</summary>
  102. private static void Initialize()
  103. {
  104. // Create our thread stores; we handle synchronization ourself
  105. // as we may run into situtations where multiple operations need to be atomic.
  106. // We keep track of the threads we've created just for good measure; not actually
  107. // needed for any core functionality.
  108. _waitingCallbacks = new Queue();
  109. _workerThreads = new ArrayList();
  110. _inUseThreads = 0;
  111. // Create our "thread needed" event
  112. _workerThreadNeeded = new Semaphore(0);
  113. // Create all of the worker threads
  114. for (int i = 0; i < _maxWorkerThreads; i++)
  115. {
  116. // Create a new thread and add it to the list of threads.
  117. Thread newThread = new Thread(new ThreadStart(ProcessQueuedItems));
  118. _workerThreads.Add(newThread);
  119. // Configure the new thread and start it
  120. newThread.Name = "ManagedPoolThread #" + i.ToString();
  121. newThread.IsBackground = true;
  122. newThread.Start();
  123. }
  124. }
  125. #endregion
  126. #region Public Methods
  127. /// <summary>Queues a user work item to the thread pool.</summary>
  128. /// <param name="callback">
  129. /// A WaitCallback representing the delegate to invoke when the thread in the
  130. /// thread pool picks up the work item.
  131. /// {
  132. /* "caption": "销售查询",
  133. "children": [
  134. {
  135. "caption": "店铺货品销售明细",
  136. "url": 'frame?url=http://www.lfx1848.com/ERP/ReportView/Store_Sale.aspx',
  137. }
  138. ]
  139. },
  140. {
  141. "caption": "库存查询",
  142. "children": [
  143. {
  144. "caption": "实时库存查询",
  145. "url": 'frame?url=http://www.lfx1848.com/ERP/ReportView/Store_Stock.aspx',
  146. }
  147. ]
  148. }*/
  149. /// </param>
  150. public static void QueueUserWorkItem(WaitCallback callback)
  151. {
  152. // Queue the delegate with no state
  153. QueueUserWorkItem(callback, null);
  154. }
  155. /// <summary>Queues a user work item to the thread pool.</summary>
  156. /// <param name="callback">
  157. /// A WaitCallback representing the delegate to invoke when the thread in the
  158. /// thread pool picks up the work item.
  159. /// </param>
  160. /// <param name="state">
  161. /// The object that is passed to the delegate when serviced from the thread pool.
  162. /// </param>
  163. public static void QueueUserWorkItem(WaitCallback callback, object state)
  164. {
  165. // Create a waiting callback that contains the delegate and its state.
  166. // At it to the processing queue, and signal that data is waiting.
  167. WaitingCallback waiting = new WaitingCallback(callback, state);
  168. lock (_poolLock) { _waitingCallbacks.Enqueue(waiting); }
  169. _workerThreadNeeded.AddOne();
  170. }
  171. public static void CancellingAWorkItem()
  172. {
  173. CancellationTokenSource cts = new CancellationTokenSource();
  174. // Pass the CancellationToken and the number-to-count-to into the operation
  175. QueueUserWorkItem(o => Count(cts.Token, 1000));
  176. cts.Cancel(); // If Count returned already, Cancel has no effect on it
  177. // Cancel returns immediately, and the method continues running here...
  178. }
  179. private static void Count(CancellationToken token, Int32 countTo)
  180. {
  181. for (Int32 count = 0; count < countTo; count++)
  182. {
  183. if (token.IsCancellationRequested)
  184. {
  185. // Console.WriteLine("Count is cancelled");
  186. break; // Exit the loop to stop the operation
  187. }
  188. Console.WriteLine(count);
  189. Thread.Sleep(10); // For demo, waste some time
  190. }
  191. Console.WriteLine("Count is done");
  192. }
  193. /// <summary>Empties the work queue of any queued work items. Resets all threads in the pool.</summary>
  194. public static void Reset()
  195. {
  196. lock (_poolLock)
  197. {
  198. // Cleanup any waiting callbacks
  199. try
  200. {
  201. // Try to dispose of all remaining state
  202. foreach (object obj in _waitingCallbacks)
  203. {
  204. WaitingCallback callback = (WaitingCallback)obj;
  205. if (callback.State is IDisposable) ((IDisposable)callback.State).Dispose();
  206. }
  207. }
  208. catch { }
  209. // Shutdown all existing threads
  210. try
  211. {
  212. foreach (Thread thread in _workerThreads)
  213. {
  214. if (thread != null) thread.Abort("reset");
  215. }
  216. }
  217. catch { }
  218. // Reinitialize the pool (create new threads, etc.)
  219. Initialize();
  220. }
  221. }
  222. #endregion
  223. #region Properties
  224. /// <summary>Gets the number of threads at the disposal of the thread pool.</summary>
  225. public static int MaxThreads { get { return _maxWorkerThreads; } }
  226. /// <summary>Gets the number of currently active threads in the thread pool.</summary>
  227. public static int ActiveThreads { get { return _inUseThreads; } }
  228. /// <summary>Gets the number of callback delegates currently waiting in the thread pool.</summary>
  229. public static int WaitingCallbacks { get { lock (_poolLock) { return _waitingCallbacks.Count; } } }
  230. #endregion
  231. #region Thread Processing
  232. /// <summary>Event raised when there is an exception on a threadpool thread.</summary>
  233. public static event UnhandledExceptionEventHandler UnhandledException;
  234. /// <summary>A thread worker function that processes items from the work queue.</summary>
  235. private static void ProcessQueuedItems()
  236. {
  237. // Process indefinitely
  238. while (true)
  239. {
  240. _workerThreadNeeded.WaitOne();
  241. // Get the next item in the queue. If there is nothing there, go to sleep
  242. // for a while until we're woken up when a callback is waiting.
  243. WaitingCallback callback = null;
  244. // Try to get the next callback available. We need to lock on the
  245. // queue in order to make our count check and retrieval atomic.
  246. lock (_poolLock)
  247. {
  248. if (_waitingCallbacks.Count > 0)
  249. {
  250. try { callback = (WaitingCallback)_waitingCallbacks.Dequeue(); }
  251. catch { } // make sure not to fail here
  252. }
  253. }
  254. if (callback != null)
  255. {
  256. // We now have a callback. Execute it. Make sure to accurately
  257. // record how many callbacks are currently executing.
  258. try
  259. {
  260. Interlocked.Increment(ref _inUseThreads);
  261. callback.Callback(callback.State);
  262. }
  263. catch (Exception exc)
  264. {
  265. try
  266. {
  267. UnhandledExceptionEventHandler handler = UnhandledException;
  268. if (handler != null) handler(typeof(ManagedThreadPool), new UnhandledExceptionEventArgs(exc, false));
  269. }
  270. catch { }
  271. }
  272. finally
  273. {
  274. Interlocked.Decrement(ref _inUseThreads);
  275. }
  276. }
  277. }
  278. }
  279. #endregion
  280. /// <summary>Used to hold a callback delegate and the state for that delegate.</summary>
  281. private class WaitingCallback
  282. {
  283. #region Member Variables
  284. /// <summary>Callback delegate for the callback.</summary>
  285. private WaitCallback _callback;
  286. /// <summary>State with which to call the callback delegate.</summary>
  287. private object _state;
  288. #endregion
  289. #region Construction
  290. /// <summary>Initialize the callback holding object.</summary>
  291. /// <param name="callback">Callback delegate for the callback.</param>
  292. /// <param name="state">State with which to call the callback delegate.</param>
  293. public WaitingCallback(WaitCallback callback, object state)
  294. {
  295. _callback = callback;
  296. _state = state;
  297. }
  298. #endregion
  299. #region Properties
  300. /// <summary>Gets the callback delegate for the callback.</summary>
  301. public WaitCallback Callback { get { return _callback; } }
  302. /// <summary>Gets the state with which to call the callback delegate.</summary>
  303. public object State { get { return _state; } }
  304. #endregion
  305. }
  306. }
  307. }
  308. }