UniTask
UniTask copied to clipboard
External cancellation executed on a different thread
Hi. I'm trying to use .AttachExternalCancellation(token) and noticed that when a task is cancelled externally, the code following await is executed on a different thread. Is this expected behavior?
Wish it to be documented somewhere, because this is something we don't expect when using UniTasks with Unity. Attempts to access Unity objects in this case result in an exception.
Code to reproduce issue (run in UnityEditor):
Debug.Log($"Starting, Thread: {Thread.CurrentThread.ManagedThreadId}");
TimeSpan mainTaskTime = TimeSpan.FromSeconds(1);
TimeSpan cancellationTimeout = TimeSpan.FromSeconds(0.1f);
using var cts = new CancellationTokenSource(cancellationTimeout);
bool isCancelled = await UniTask.Delay(mainTaskTime, cancellationToken: default)
.AttachExternalCancellation(cts.Token)
.SuppressCancellationThrow();
if (isCancelled)
Debug.LogWarning($"Cancelled: Thread: {Thread.CurrentThread.ManagedThreadId}");
else
Debug.Log($"Completed: Thread: {Thread.CurrentThread.ManagedThreadId}");
Actual Output:
Starting, Thread: 1
Cancelled: Thread: 1564
Expected Output:
Starting, Thread: 1
Cancelled: Thread: 1