diff --git a/src/UniTask/Assets/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs b/src/UniTask/Assets/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs index d7cd06b..c139acc 100644 --- a/src/UniTask/Assets/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs +++ b/src/UniTask/Assets/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs @@ -18,11 +18,32 @@ namespace Cysharp.Threading.Tasks return cts.Token; } - public static CancellationToken ToCancellationToken(this UniTask task) + public static CancellationToken ToCancellationToken(this UniTask task, CancellationToken linkToken) { + if (linkToken.IsCancellationRequested) + { + return linkToken; + } + + if (!linkToken.CanBeCanceled) + { + return ToCancellationToken(task); + } + var cts = new CancellationTokenSource(); ToCancellationTokenCore(task, cts).Forget(); - return cts.Token; + + return CancellationTokenSource.CreateLinkedTokenSource(linkToken).Token; + } + + public static CancellationToken ToCancellationToken(this UniTask task) + { + return ToCancellationToken(task.AsUniTask()); + } + + public static CancellationToken ToCancellationToken(this UniTask task, CancellationToken linkToken) + { + return ToCancellationToken(task.AsUniTask(), linkToken); } static async UniTaskVoid ToCancellationTokenCore(UniTask task, CancellationTokenSource cts) diff --git a/src/UniTask/Assets/Scenes/SandboxMain.cs b/src/UniTask/Assets/Scenes/SandboxMain.cs index 2f2b0bb..d75fb3e 100644 --- a/src/UniTask/Assets/Scenes/SandboxMain.cs +++ b/src/UniTask/Assets/Scenes/SandboxMain.cs @@ -434,16 +434,31 @@ public class SandboxMain : MonoBehaviour throw new Exception("yeah"); } - - void Start() + + async UniTaskVoid Start() { - _ = Foo(); // unhandled. - Go(); + //_ = Foo(); // unhandled. + //Go(); + var cts = new CancellationTokenSource(); + + okButton.onClick.AddListener(() => + { + cts.Cancel(); + }); + UnityEngine.Debug.Log("Start:" + PlayerLoopInfo.CurrentLoopType); + var token = UniTask.Delay(TimeSpan.FromSeconds(3), DelayType.Realtime).ToCancellationToken(cts.Token); + while (!token.IsCancellationRequested) + { + UnityEngine.Debug.Log("in loop"); + await UniTask.Yield(); + } + UnityEngine.Debug.Log("end"); + // this.GetCancellationTokenOnDestroy() diff --git a/src/UniTask/Assets/Tests/DelayTest.cs b/src/UniTask/Assets/Tests/DelayTest.cs index 25de6e2..7102f4e 100644 --- a/src/UniTask/Assets/Tests/DelayTest.cs +++ b/src/UniTask/Assets/Tests/DelayTest.cs @@ -190,7 +190,7 @@ namespace Cysharp.Threading.TasksTests { var now = DateTimeOffset.UtcNow; - await UniTask.DelayRealtime(TimeSpan.FromSeconds(2)); + await UniTask.Delay(TimeSpan.FromSeconds(2), DelayType.Realtime); var elapsed = DateTimeOffset.UtcNow - now;