AsyncOperation.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 ManualResetEventSlim _resetEvent;
  14. private T _result;
  15. private Exception _exception;
  16. private AsyncOperation(Func<T> producer)
  17. {
  18. _producer = producer;
  19. _resetEvent = new ManualResetEventSlim(initialState: false);
  20. }
  21. public static AsyncOperation<T> Run(Func<T> producer)
  22. {
  23. var task = new AsyncOperation<T>(producer);
  24. task.Run();
  25. return task;
  26. }
  27. private void Run()
  28. {
  29. ThreadPool.QueueUserWorkItem(_ =>
  30. {
  31. try
  32. {
  33. _result = _producer();
  34. }
  35. catch (Exception e)
  36. {
  37. _exception = e;
  38. }
  39. finally
  40. {
  41. _resetEvent.Set();
  42. }
  43. });
  44. }
  45. private void CheckCompletion()
  46. {
  47. if (!_resetEvent.IsSet)
  48. _resetEvent.Wait();
  49. }
  50. public T Result
  51. {
  52. get
  53. {
  54. CheckCompletion();
  55. return _result;
  56. }
  57. }
  58. public Exception Exception
  59. {
  60. get
  61. {
  62. CheckCompletion();
  63. return _exception;
  64. }
  65. }
  66. }
  67. }