UniTask icon indicating copy to clipboard operation
UniTask copied to clipboard

External cancellation executed on a different thread

Open pspgit opened this issue 2 months ago • 0 comments

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

pspgit avatar Oct 12 '25 14:10 pspgit