ExceptionHelper.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.IO;
  5. using System.Threading;
  6. namespace System.Reactive
  7. {
  8. /// <summary>
  9. /// Utility methods to handle lock-free combining of Exceptions
  10. /// as well as hosting a terminal-exception indicator for
  11. /// lock-free termination support.
  12. /// </summary>
  13. internal static class ExceptionHelper
  14. {
  15. /// <summary>
  16. /// The singleton instance of the exception indicating a terminal state,
  17. /// DO NOT LEAK or signal this via OnError!
  18. /// </summary>
  19. public static Exception Terminated { get; } = new EndOfStreamException("On[Error|Completed]");
  20. /// <summary>
  21. /// Tries to atomically set the Exception on the given field if it is
  22. /// still null.
  23. /// </summary>
  24. /// <param name="field">The target field to try to set atomically.</param>
  25. /// <param name="ex">The exception to set, not null (not verified).</param>
  26. /// <returns>True if the operation succeeded, false if the target was not null.</returns>
  27. public static bool TrySetException(ref Exception? field, Exception ex)
  28. {
  29. return Interlocked.CompareExchange(ref field, ex, null) == null;
  30. }
  31. }
  32. }