CancellationTokenSourceExtensions.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
  2. using System.Threading;
  3. using UnityEngine;
  4. using Cysharp.Threading.Tasks.Triggers;
  5. using System;
  6. using Cysharp.Threading.Tasks.Internal;
  7. namespace Cysharp.Threading.Tasks
  8. {
  9. public static partial class CancellationTokenSourceExtensions
  10. {
  11. readonly static Action<object> CancelCancellationTokenSourceStateDelegate = new Action<object>(CancelCancellationTokenSourceState);
  12. static void CancelCancellationTokenSourceState(object state)
  13. {
  14. var cts = (CancellationTokenSource)state;
  15. cts.Cancel();
  16. }
  17. public static IDisposable CancelAfterSlim(this CancellationTokenSource cts, int millisecondsDelay, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update)
  18. {
  19. return CancelAfterSlim(cts, TimeSpan.FromMilliseconds(millisecondsDelay), delayType, delayTiming);
  20. }
  21. public static IDisposable CancelAfterSlim(this CancellationTokenSource cts, TimeSpan delayTimeSpan, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update)
  22. {
  23. return PlayerLoopTimer.StartNew(delayTimeSpan, false, delayType, delayTiming, cts.Token, CancelCancellationTokenSourceStateDelegate, cts);
  24. }
  25. public static void RegisterRaiseCancelOnDestroy(this CancellationTokenSource cts, Component component)
  26. {
  27. RegisterRaiseCancelOnDestroy(cts, component.gameObject);
  28. }
  29. public static void RegisterRaiseCancelOnDestroy(this CancellationTokenSource cts, GameObject gameObject)
  30. {
  31. var trigger = gameObject.GetAsyncDestroyTrigger();
  32. trigger.CancellationToken.RegisterWithoutCaptureExecutionContext(CancelCancellationTokenSourceStateDelegate, cts);
  33. }
  34. }
  35. }