WorkItem.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. // Ami Bar
  2. // [email protected]
  3. using System;
  4. using System.Threading;
  5. using System.Diagnostics;
  6. namespace Amib.Threading.Internal
  7. {
  8. #region WorkItem Delegate
  9. /// <summary>
  10. /// An internal delegate to call when the WorkItem starts or completes
  11. /// </summary>
  12. internal delegate void WorkItemStateCallback(WorkItem workItem);
  13. #endregion
  14. #region IInternalWorkItemResult interface
  15. public class CanceledWorkItemsGroup
  16. {
  17. public readonly static CanceledWorkItemsGroup NotCanceledWorkItemsGroup = new CanceledWorkItemsGroup();
  18. private bool _isCanceled = false;
  19. public bool IsCanceled
  20. {
  21. get { return _isCanceled; }
  22. set { _isCanceled = value; }
  23. }
  24. }
  25. internal interface IInternalWorkItemResult
  26. {
  27. event WorkItemStateCallback OnWorkItemStarted;
  28. event WorkItemStateCallback OnWorkItemCompleted;
  29. }
  30. #endregion
  31. #region IWorkItem interface
  32. public interface IWorkItem
  33. {
  34. }
  35. #endregion
  36. #region WorkItem class
  37. /// <summary>
  38. /// Holds a callback delegate and the state for that delegate.
  39. /// </summary>
  40. public class WorkItem : IHasWorkItemPriority, IWorkItem
  41. {
  42. #region WorkItemState enum
  43. /// <summary>
  44. /// Indicates the state of the work item in the thread pool
  45. /// </summary>
  46. private enum WorkItemState
  47. {
  48. InQueue,
  49. InProgress,
  50. Completed,
  51. Canceled,
  52. }
  53. #endregion
  54. #region Member Variables
  55. public Thread currentThread;
  56. /// <summary>
  57. /// Callback delegate for the callback.
  58. /// </summary>
  59. private WorkItemCallback _callback;
  60. /// <summary>
  61. /// State with which to call the callback delegate.
  62. /// </summary>
  63. private object _state;
  64. /// <summary>
  65. /// Stores the caller's context
  66. /// </summary>
  67. private CallerThreadContext _callerContext;
  68. /// <summary>
  69. /// Holds the result of the mehtod
  70. /// </summary>
  71. private object _result;
  72. /// <summary>
  73. /// Hold the exception if the method threw it
  74. /// </summary>
  75. private Exception _exception;
  76. /// <summary>
  77. /// Hold the state of the work item
  78. /// </summary>
  79. private WorkItemState _workItemState;
  80. /// <summary>
  81. /// A ManualResetEvent to indicate that the result is ready
  82. /// </summary>
  83. private ManualResetEvent _workItemCompleted;
  84. /// <summary>
  85. /// A reference count to the _workItemCompleted.
  86. /// When it reaches to zero _workItemCompleted is Closed
  87. /// </summary>
  88. private int _workItemCompletedRefCount;
  89. /// <summary>
  90. /// Represents the result state of the work item
  91. /// </summary>
  92. private WorkItemResult _workItemResult;
  93. /// <summary>
  94. /// Work item info
  95. /// </summary>
  96. private WorkItemInfo _workItemInfo;
  97. /// <summary>
  98. /// Called when the WorkItem starts
  99. /// </summary>
  100. private event WorkItemStateCallback _workItemStartedEvent;
  101. /// <summary>
  102. /// Called when the WorkItem completes
  103. /// </summary>
  104. private event WorkItemStateCallback _workItemCompletedEvent;
  105. /// <summary>
  106. /// A reference to an object that indicates whatever the
  107. /// WorkItemsGroup has been canceled
  108. /// </summary>
  109. private CanceledWorkItemsGroup _canceledWorkItemsGroup = CanceledWorkItemsGroup.NotCanceledWorkItemsGroup;
  110. /// <summary>
  111. /// The work item group this work item belong to.
  112. ///
  113. /// </summary>
  114. private IWorkItemsGroup _workItemsGroup;
  115. #region Performance Counter fields
  116. /// <summary>
  117. /// The time when the work items is queued.
  118. /// Used with the performance counter.
  119. /// </summary>
  120. private DateTime _queuedTime;
  121. /// <summary>
  122. /// The time when the work items starts its execution.
  123. /// Used with the performance counter.
  124. /// </summary>
  125. private DateTime _beginProcessTime;
  126. /// <summary>
  127. /// The time when the work items ends its execution.
  128. /// Used with the performance counter.
  129. /// </summary>
  130. private DateTime _endProcessTime;
  131. #endregion
  132. #endregion
  133. #region Properties
  134. public TimeSpan WaitingTime
  135. {
  136. get
  137. {
  138. return (_beginProcessTime - _queuedTime);
  139. }
  140. }
  141. public TimeSpan ProcessTime
  142. {
  143. get
  144. {
  145. return (_endProcessTime - _beginProcessTime);
  146. }
  147. }
  148. #endregion
  149. #region Construction
  150. /// <summary>
  151. /// Initialize the callback holding object.
  152. /// </summary>
  153. /// <param name="callback">Callback delegate for the callback.</param>
  154. /// <param name="state">State with which to call the callback delegate.</param>
  155. ///
  156. /// We assume that the WorkItem object is created within the thread
  157. /// that meant to run the callback
  158. public WorkItem(
  159. IWorkItemsGroup workItemsGroup,
  160. WorkItemInfo workItemInfo,
  161. WorkItemCallback callback,
  162. object state)
  163. {
  164. _workItemsGroup = workItemsGroup;
  165. _workItemInfo = workItemInfo;
  166. if (_workItemInfo.UseCallerCallContext || _workItemInfo.UseCallerHttpContext)
  167. {
  168. _callerContext = CallerThreadContext.Capture(_workItemInfo.UseCallerCallContext, _workItemInfo.UseCallerHttpContext);
  169. }
  170. _callback = callback;
  171. _state = state;
  172. _workItemResult = new WorkItemResult(this);
  173. Initialize();
  174. }
  175. internal void Initialize()
  176. {
  177. _workItemState = WorkItemState.InQueue;
  178. _workItemCompleted = null;
  179. _workItemCompletedRefCount = 0;
  180. }
  181. internal bool WasQueuedBy(IWorkItemsGroup workItemsGroup)
  182. {
  183. return (workItemsGroup == _workItemsGroup);
  184. }
  185. #endregion
  186. #region Methods
  187. public CanceledWorkItemsGroup CanceledWorkItemsGroup
  188. {
  189. get
  190. {
  191. return _canceledWorkItemsGroup;
  192. }
  193. set
  194. {
  195. _canceledWorkItemsGroup = value;
  196. }
  197. }
  198. /// <summary>
  199. /// Change the state of the work item to in progress if it wasn't canceled.
  200. /// </summary>
  201. /// <returns>
  202. /// Return true on success or false in case the work item was canceled.
  203. /// If the work item needs to run a post execute then the method will return true.
  204. /// </returns>
  205. public bool StartingWorkItem()
  206. {
  207. _beginProcessTime = DateTime.Now;
  208. lock(this)
  209. {
  210. if (IsCanceled)
  211. {
  212. bool result = false;
  213. if ((_workItemInfo.PostExecuteWorkItemCallback != null) &&
  214. ((_workItemInfo.CallToPostExecute & CallToPostExecute.WhenWorkItemCanceled) == CallToPostExecute.WhenWorkItemCanceled))
  215. {
  216. result = true;
  217. }
  218. return result;
  219. }
  220. Debug.Assert(WorkItemState.InQueue == GetWorkItemState());
  221. SetWorkItemState(WorkItemState.InProgress);
  222. }
  223. return true;
  224. }
  225. /// <summary>
  226. /// Execute the work item and the post execute
  227. /// </summary>
  228. public void Execute()
  229. {
  230. CallToPostExecute currentCallToPostExecute = 0;
  231. // Execute the work item if we are in the correct state
  232. switch(GetWorkItemState())
  233. {
  234. case WorkItemState.InProgress:
  235. currentCallToPostExecute |= CallToPostExecute.WhenWorkItemNotCanceled;
  236. ExecuteWorkItem();
  237. break;
  238. case WorkItemState.Canceled:
  239. currentCallToPostExecute |= CallToPostExecute.WhenWorkItemCanceled;
  240. break;
  241. default:
  242. Debug.Assert(false);
  243. throw new NotSupportedException();
  244. }
  245. // Run the post execute as needed
  246. if ((currentCallToPostExecute & _workItemInfo.CallToPostExecute) != 0)
  247. {
  248. PostExecute();
  249. }
  250. _endProcessTime = DateTime.Now;
  251. }
  252. internal void FireWorkItemCompleted()
  253. {
  254. try
  255. {
  256. if (null != _workItemCompletedEvent)
  257. {
  258. _workItemCompletedEvent(this);
  259. }
  260. }
  261. catch // Ignore exceptions
  262. {}
  263. }
  264. /// <summary>
  265. /// Execute the work item
  266. /// </summary>
  267. private void ExecuteWorkItem()
  268. {
  269. CallerThreadContext ctc = null;
  270. if (null != _callerContext)
  271. {
  272. ctc = CallerThreadContext.Capture(_callerContext.CapturedCallContext, _callerContext.CapturedHttpContext);
  273. CallerThreadContext.Apply(_callerContext);
  274. }
  275. Exception exception = null;
  276. object result = null;
  277. try
  278. {
  279. result = _callback(_state);
  280. }
  281. catch (Exception e)
  282. {
  283. // Save the exception so we can rethrow it later
  284. exception = e;
  285. }
  286. if (null != _callerContext)
  287. {
  288. CallerThreadContext.Apply(ctc);
  289. }
  290. SetResult(result, exception);
  291. }
  292. /// <summary>
  293. /// Runs the post execute callback
  294. /// </summary>
  295. private void PostExecute()
  296. {
  297. if (null != _workItemInfo.PostExecuteWorkItemCallback)
  298. {
  299. try
  300. {
  301. _workItemInfo.PostExecuteWorkItemCallback(this._workItemResult);
  302. }
  303. catch (Exception e)
  304. {
  305. Debug.Assert(null != e);
  306. }
  307. }
  308. }
  309. /// <summary>
  310. /// Set the result of the work item to return
  311. /// </summary>
  312. /// <param name="result">The result of the work item</param>
  313. internal void SetResult(object result, Exception exception)
  314. {
  315. _result = result;
  316. _exception = exception;
  317. SignalComplete(false);
  318. }
  319. /// <summary>
  320. /// Returns the work item result
  321. /// </summary>
  322. /// <returns>The work item result</returns>
  323. internal IWorkItemResult GetWorkItemResult()
  324. {
  325. return _workItemResult;
  326. }
  327. /// <summary>
  328. /// Wait for all work items to complete
  329. /// </summary>
  330. /// <param name="workItemResults">Array of work item result objects</param>
  331. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  332. /// <param name="exitContext">
  333. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  334. /// </param>
  335. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  336. /// <returns>
  337. /// true when every work item in workItemResults has completed; otherwise false.
  338. /// </returns>
  339. internal static bool WaitAll(
  340. IWorkItemResult [] workItemResults,
  341. int millisecondsTimeout,
  342. bool exitContext,
  343. WaitHandle cancelWaitHandle)
  344. {
  345. if (0 == workItemResults.Length)
  346. {
  347. return true;
  348. }
  349. bool success;
  350. WaitHandle [] waitHandles = new WaitHandle[workItemResults.Length];;
  351. GetWaitHandles(workItemResults, waitHandles);
  352. if ((null == cancelWaitHandle) && (waitHandles.Length <= 64))
  353. {
  354. success = WaitHandle.WaitAll(waitHandles, millisecondsTimeout, exitContext);
  355. }
  356. else
  357. {
  358. success = true;
  359. int millisecondsLeft = millisecondsTimeout;
  360. DateTime start = DateTime.Now;
  361. WaitHandle [] whs;
  362. if (null != cancelWaitHandle)
  363. {
  364. whs = new WaitHandle [] { null, cancelWaitHandle };
  365. }
  366. else
  367. {
  368. whs = new WaitHandle [] { null };
  369. }
  370. bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout);
  371. // Iterate over the wait handles and wait for each one to complete.
  372. // We cannot use WaitHandle.WaitAll directly, because the cancelWaitHandle
  373. // won't affect it.
  374. // Each iteration we update the time left for the timeout.
  375. for(int i = 0; i < workItemResults.Length; ++i)
  376. {
  377. // WaitAny don't work with negative numbers
  378. if (!waitInfinitely && (millisecondsLeft < 0))
  379. {
  380. success = false;
  381. break;
  382. }
  383. whs[0] = waitHandles[i];
  384. int result = WaitHandle.WaitAny(whs, millisecondsLeft, exitContext);
  385. if((result > 0) || (WaitHandle.WaitTimeout == result))
  386. {
  387. success = false;
  388. break;
  389. }
  390. if(!waitInfinitely)
  391. {
  392. // Update the time left to wait
  393. TimeSpan ts = DateTime.Now - start;
  394. millisecondsLeft = millisecondsTimeout - (int)ts.TotalMilliseconds;
  395. }
  396. }
  397. }
  398. // Release the wait handles
  399. ReleaseWaitHandles(workItemResults);
  400. return success;
  401. }
  402. /// <summary>
  403. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  404. /// </summary>
  405. /// <param name="workItemResults">Array of work item result objects</param>
  406. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  407. /// <param name="exitContext">
  408. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  409. /// </param>
  410. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  411. /// <returns>
  412. /// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled.
  413. /// </returns>
  414. internal static int WaitAny(
  415. IWorkItemResult [] workItemResults,
  416. int millisecondsTimeout,
  417. bool exitContext,
  418. WaitHandle cancelWaitHandle)
  419. {
  420. WaitHandle [] waitHandles = null;
  421. if (null != cancelWaitHandle)
  422. {
  423. waitHandles = new WaitHandle[workItemResults.Length+1];
  424. GetWaitHandles(workItemResults, waitHandles);
  425. waitHandles[workItemResults.Length] = cancelWaitHandle;
  426. }
  427. else
  428. {
  429. waitHandles = new WaitHandle[workItemResults.Length];
  430. GetWaitHandles(workItemResults, waitHandles);
  431. }
  432. int result = WaitHandle.WaitAny(waitHandles, millisecondsTimeout, exitContext);
  433. // Treat cancel as timeout
  434. if (null != cancelWaitHandle)
  435. {
  436. if (result == workItemResults.Length)
  437. {
  438. result = WaitHandle.WaitTimeout;
  439. }
  440. }
  441. ReleaseWaitHandles(workItemResults);
  442. return result;
  443. }
  444. /// <summary>
  445. /// Fill an array of wait handles with the work items wait handles.
  446. /// </summary>
  447. /// <param name="workItemResults">An array of work item results</param>
  448. /// <param name="waitHandles">An array of wait handles to fill</param>
  449. private static void GetWaitHandles(
  450. IWorkItemResult [] workItemResults,
  451. WaitHandle [] waitHandles)
  452. {
  453. for(int i = 0; i < workItemResults.Length; ++i)
  454. {
  455. WorkItemResult wir = workItemResults[i] as WorkItemResult;
  456. Debug.Assert(null != wir, "All workItemResults must be WorkItemResult objects");
  457. waitHandles[i] = wir.GetWorkItem().GetWaitHandle();
  458. }
  459. }
  460. /// <summary>
  461. /// Release the work items' wait handles
  462. /// </summary>
  463. /// <param name="workItemResults">An array of work item results</param>
  464. private static void ReleaseWaitHandles(IWorkItemResult [] workItemResults)
  465. {
  466. for(int i = 0; i < workItemResults.Length; ++i)
  467. {
  468. WorkItemResult wir = workItemResults[i] as WorkItemResult;
  469. wir.GetWorkItem().ReleaseWaitHandle();
  470. }
  471. }
  472. #endregion
  473. #region Private Members
  474. private WorkItemState GetWorkItemState()
  475. {
  476. if (_canceledWorkItemsGroup.IsCanceled)
  477. {
  478. return WorkItemState.Canceled;
  479. }
  480. return _workItemState;
  481. }
  482. /// <summary>
  483. /// Sets the work item's state
  484. /// </summary>
  485. /// <param name="workItemState">The state to set the work item to</param>
  486. private void SetWorkItemState(WorkItemState workItemState)
  487. {
  488. lock(this)
  489. {
  490. _workItemState = workItemState;
  491. }
  492. }
  493. /// <summary>
  494. /// Signals that work item has been completed or canceled
  495. /// </summary>
  496. /// <param name="canceled">Indicates that the work item has been canceled</param>
  497. private void SignalComplete(bool canceled)
  498. {
  499. SetWorkItemState(canceled ? WorkItemState.Canceled : WorkItemState.Completed);
  500. lock(this)
  501. {
  502. // If someone is waiting then signal.
  503. if (null != _workItemCompleted)
  504. {
  505. _workItemCompleted.Set();
  506. }
  507. }
  508. }
  509. internal void WorkItemIsQueued()
  510. {
  511. _queuedTime = DateTime.Now;
  512. }
  513. #endregion
  514. #region Members exposed by WorkItemResult
  515. /// <summary>
  516. /// Cancel the work item if it didn't start running yet.
  517. /// </summary>
  518. /// <returns>Returns true on success or false if the work item is in progress or already completed</returns>
  519. private bool Cancel()
  520. {
  521. lock(this)
  522. {
  523. switch(GetWorkItemState())
  524. {
  525. case WorkItemState.Canceled:
  526. //Debug.WriteLine("Work item already canceled");
  527. return true;
  528. case WorkItemState.Completed:
  529. case WorkItemState.InProgress:
  530. //Debug.WriteLine("Work item cannot be canceled");
  531. return false;
  532. case WorkItemState.InQueue:
  533. // Signal to the wait for completion that the work
  534. // item has been completed (canceled). There is no
  535. // reason to wait for it to get out of the queue
  536. SignalComplete(true);
  537. //Debug.WriteLine("Work item canceled");
  538. return true;
  539. }
  540. }
  541. return false;
  542. }
  543. /// <summary>
  544. /// Get the result of the work item.
  545. /// If the work item didn't run yet then the caller waits for the result, timeout, or cancel.
  546. /// In case of error the method throws and exception
  547. /// </summary>
  548. /// <returns>The result of the work item</returns>
  549. private object GetResult(
  550. int millisecondsTimeout,
  551. bool exitContext,
  552. WaitHandle cancelWaitHandle)
  553. {
  554. Exception e = null;
  555. object result = GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e);
  556. if (null != e)
  557. {
  558. throw new WorkItemResultException("The work item caused an excpetion, see the inner exception for details", e);
  559. }
  560. return result;
  561. }
  562. /// <summary>
  563. /// Get the result of the work item.
  564. /// If the work item didn't run yet then the caller waits for the result, timeout, or cancel.
  565. /// In case of error the e argument is filled with the exception
  566. /// </summary>
  567. /// <returns>The result of the work item</returns>
  568. private object GetResult(
  569. int millisecondsTimeout,
  570. bool exitContext,
  571. WaitHandle cancelWaitHandle,
  572. out Exception e)
  573. {
  574. e = null;
  575. // Check for cancel
  576. if (WorkItemState.Canceled == GetWorkItemState())
  577. {
  578. throw new WorkItemCancelException("Work item canceled");
  579. }
  580. // Check for completion
  581. if (IsCompleted)
  582. {
  583. e = _exception;
  584. return _result;
  585. }
  586. // If no cancelWaitHandle is provided
  587. if (null == cancelWaitHandle)
  588. {
  589. WaitHandle wh = GetWaitHandle();
  590. bool timeout = !wh.WaitOne(millisecondsTimeout, exitContext);
  591. ReleaseWaitHandle();
  592. if (timeout)
  593. {
  594. throw new WorkItemTimeoutException("Work item timeout");
  595. }
  596. }
  597. else
  598. {
  599. WaitHandle wh = GetWaitHandle();
  600. int result = WaitHandle.WaitAny(new WaitHandle[] { wh, cancelWaitHandle });
  601. ReleaseWaitHandle();
  602. switch(result)
  603. {
  604. case 0:
  605. // The work item signaled
  606. // Note that the signal could be also as a result of canceling the
  607. // work item (not the get result)
  608. break;
  609. case 1:
  610. case WaitHandle.WaitTimeout:
  611. throw new WorkItemTimeoutException("Work item timeout");
  612. default:
  613. Debug.Assert(false);
  614. break;
  615. }
  616. }
  617. // Check for cancel
  618. if (WorkItemState.Canceled == GetWorkItemState())
  619. {
  620. throw new WorkItemCancelException("Work item canceled");
  621. }
  622. Debug.Assert(IsCompleted);
  623. e = _exception;
  624. // Return the result
  625. return _result;
  626. }
  627. /// <summary>
  628. /// A wait handle to wait for completion, cancel, or timeout
  629. /// </summary>
  630. private WaitHandle GetWaitHandle()
  631. {
  632. lock(this)
  633. {
  634. if (null == _workItemCompleted)
  635. {
  636. _workItemCompleted = new ManualResetEvent(IsCompleted);
  637. }
  638. ++_workItemCompletedRefCount;
  639. }
  640. return _workItemCompleted;
  641. }
  642. private void ReleaseWaitHandle()
  643. {
  644. lock(this)
  645. {
  646. if (null != _workItemCompleted)
  647. {
  648. --_workItemCompletedRefCount;
  649. if (0 == _workItemCompletedRefCount)
  650. {
  651. _workItemCompleted.Close();
  652. _workItemCompleted = null;
  653. }
  654. }
  655. }
  656. }
  657. /// <summary>
  658. /// Returns true when the work item has completed or canceled
  659. /// </summary>
  660. private bool IsCompleted
  661. {
  662. get
  663. {
  664. lock(this)
  665. {
  666. WorkItemState workItemState = GetWorkItemState();
  667. return ((workItemState == WorkItemState.Completed) ||
  668. (workItemState == WorkItemState.Canceled));
  669. }
  670. }
  671. }
  672. /// <summary>
  673. /// Returns true when the work item has canceled
  674. /// </summary>
  675. public bool IsCanceled
  676. {
  677. get
  678. {
  679. lock(this)
  680. {
  681. return (GetWorkItemState() == WorkItemState.Canceled);
  682. }
  683. }
  684. }
  685. #endregion
  686. #region IHasWorkItemPriority Members
  687. /// <summary>
  688. /// Returns the priority of the work item
  689. /// </summary>
  690. public WorkItemPriority WorkItemPriority
  691. {
  692. get
  693. {
  694. return _workItemInfo.WorkItemPriority;
  695. }
  696. }
  697. #endregion
  698. internal event WorkItemStateCallback OnWorkItemStarted
  699. {
  700. add
  701. {
  702. _workItemStartedEvent += value;
  703. }
  704. remove
  705. {
  706. _workItemStartedEvent -= value;
  707. }
  708. }
  709. internal event WorkItemStateCallback OnWorkItemCompleted
  710. {
  711. add
  712. {
  713. _workItemCompletedEvent += value;
  714. }
  715. remove
  716. {
  717. _workItemCompletedEvent -= value;
  718. }
  719. }
  720. #region WorkItemResult class
  721. private class WorkItemResult : IWorkItemResult, IInternalWorkItemResult
  722. {
  723. /// <summary>
  724. /// A back reference to the work item
  725. /// </summary>
  726. private WorkItem _workItem;
  727. public WorkItemResult(WorkItem workItem)
  728. {
  729. _workItem = workItem;
  730. }
  731. internal WorkItem GetWorkItem()
  732. {
  733. return _workItem;
  734. }
  735. #region IWorkItemResult Members
  736. public bool IsCompleted
  737. {
  738. get
  739. {
  740. return _workItem.IsCompleted;
  741. }
  742. }
  743. public void Abort()
  744. {
  745. _workItem.Abort();
  746. }
  747. public bool IsCanceled
  748. {
  749. get
  750. {
  751. return _workItem.IsCanceled;
  752. }
  753. }
  754. public object GetResult()
  755. {
  756. return _workItem.GetResult(Timeout.Infinite, true, null);
  757. }
  758. public object GetResult(int millisecondsTimeout, bool exitContext)
  759. {
  760. return _workItem.GetResult(millisecondsTimeout, exitContext, null);
  761. }
  762. public object GetResult(TimeSpan timeout, bool exitContext)
  763. {
  764. return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, null);
  765. }
  766. public object GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle)
  767. {
  768. return _workItem.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle);
  769. }
  770. public object GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle)
  771. {
  772. return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
  773. }
  774. public object GetResult(out Exception e)
  775. {
  776. return _workItem.GetResult(Timeout.Infinite, true, null, out e);
  777. }
  778. public object GetResult(int millisecondsTimeout, bool exitContext, out Exception e)
  779. {
  780. return _workItem.GetResult(millisecondsTimeout, exitContext, null, out e);
  781. }
  782. public object GetResult(TimeSpan timeout, bool exitContext, out Exception e)
  783. {
  784. return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, null, out e);
  785. }
  786. public object GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e)
  787. {
  788. return _workItem.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e);
  789. }
  790. public object GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e)
  791. {
  792. return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle, out e);
  793. }
  794. public bool Cancel()
  795. {
  796. return _workItem.Cancel();
  797. }
  798. public object State
  799. {
  800. get
  801. {
  802. return _workItem._state;
  803. }
  804. }
  805. public WorkItemPriority WorkItemPriority
  806. {
  807. get
  808. {
  809. return _workItem._workItemInfo.WorkItemPriority;
  810. }
  811. }
  812. /// <summary>
  813. /// Return the result, same as GetResult()
  814. /// </summary>
  815. public object Result
  816. {
  817. get { return GetResult(); }
  818. }
  819. /// <summary>
  820. /// Returns the exception if occured otherwise returns null.
  821. /// This value is valid only after the work item completed,
  822. /// before that it is always null.
  823. /// </summary>
  824. public object Exception
  825. {
  826. get { return _workItem._exception; }
  827. }
  828. #endregion
  829. #region IInternalWorkItemResult Members
  830. public event WorkItemStateCallback OnWorkItemStarted
  831. {
  832. add
  833. {
  834. _workItem.OnWorkItemStarted += value;
  835. }
  836. remove
  837. {
  838. _workItem.OnWorkItemStarted -= value;
  839. }
  840. }
  841. public event WorkItemStateCallback OnWorkItemCompleted
  842. {
  843. add
  844. {
  845. _workItem.OnWorkItemCompleted += value;
  846. }
  847. remove
  848. {
  849. _workItem.OnWorkItemCompleted -= value;
  850. }
  851. }
  852. #endregion
  853. }
  854. #endregion
  855. public void DisposeOfState()
  856. {
  857. if (_workItemInfo.DisposeOfStateObjects)
  858. {
  859. IDisposable disp = _state as IDisposable;
  860. if (null != disp)
  861. {
  862. disp.Dispose();
  863. _state = null;
  864. }
  865. }
  866. }
  867. public void Abort()
  868. {
  869. lock (this)
  870. {
  871. if(currentThread != null)
  872. currentThread.Abort();
  873. }
  874. }
  875. }
  876. #endregion
  877. }