Sin descripción
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AsyncOperation.cs 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Unity Technologies.
  3. * Copyright (c) Microsoft Corporation. All rights reserved.
  4. * Licensed under the MIT License. See License.txt in the project root for license information.
  5. *--------------------------------------------------------------------------------------------*/
  6. using System;
  7. using System.Threading;
  8. namespace Microsoft.Unity.VisualStudio.Editor
  9. {
  10. internal class AsyncOperation<T>
  11. {
  12. private readonly Func<T> _producer;
  13. private readonly Func<Exception, T> _exceptionHandler;
  14. private readonly Action _finalHandler;
  15. private readonly ManualResetEventSlim _resetEvent;
  16. private T _result;
  17. private Exception _exception;
  18. private AsyncOperation(Func<T> producer, Func<Exception, T> exceptionHandler, Action finalHandler)
  19. {
  20. _producer = producer;
  21. _exceptionHandler = exceptionHandler;
  22. _finalHandler = finalHandler;
  23. _resetEvent = new ManualResetEventSlim(initialState: false);
  24. }
  25. public static AsyncOperation<T> Run(Func<T> producer, Func<Exception, T> exceptionHandler = null, Action finalHandler = null)
  26. {
  27. var task = new AsyncOperation<T>(producer, exceptionHandler, finalHandler);
  28. task.Run();
  29. return task;
  30. }
  31. private void Run()
  32. {
  33. ThreadPool.QueueUserWorkItem(_ =>
  34. {
  35. try
  36. {
  37. _result = _producer();
  38. }
  39. catch (Exception e)
  40. {
  41. _exception = e;
  42. if (_exceptionHandler != null)
  43. {
  44. _result = _exceptionHandler(e);
  45. }
  46. }
  47. finally
  48. {
  49. _finalHandler?.Invoke();
  50. _resetEvent.Set();
  51. }
  52. });
  53. }
  54. private void CheckCompletion()
  55. {
  56. if (!_resetEvent.IsSet)
  57. _resetEvent.Wait();
  58. }
  59. public T Result
  60. {
  61. get
  62. {
  63. CheckCompletion();
  64. return _result;
  65. }
  66. }
  67. public Exception Exception
  68. {
  69. get
  70. {
  71. CheckCompletion();
  72. return _exception;
  73. }
  74. }
  75. }
  76. }