UniTask icon indicating copy to clipboard operation
UniTask copied to clipboard

Unitask.Delay is not affected by calling cancel on CancellationTokenSource during unit tests.

Open eliatlas opened this issue 2 years ago • 1 comments

Issue description

I expect Unitask delay to be cancelled when I call _cts.Cancel(); But it continues the delay although Cancel() was called. One thing that I notice is that Time.realtimeSinceStartup is reset in between, so I am guessing that PlayerLoop maybe stops receiving cancel updates somewhere when playModeStateChanged is fired?

My code

_cts = new CancellationTokenSource();
var waitedLongEnough = 0;
do
{
    Debug.Log($"Wait a little more {Time.realtimeSinceStartup}");
    var delayFinished = await UniTask.Delay(TimeSpan.FromMilliseconds(100), cancellationToken: _cts.Token).SuppressCancellationThrow();
    Debug.Log($"Waited for {waitedLongEnough} delayFinished {delayFinished} {Time.realtimeSinceStartup}");
    waitedLongEnough += 100;
}
while (waitedLongEnough < StatusUpdatePeriodMs && _cts != null);

I am running Dispose() function on destroy, which looks like this:

public void Dispose()
{
    Debug.Log($"Dispose {_cts}");
    if (_cts != null)
    {
        _cts.Cancel();
        _cts.Dispose();
        _cts = null;
    }
}

During [UnityTearDown] I am checking if there are any pending unitasks, and I can see that Delay UniTask is pending. Tried to figure out maybe PlayerLoop is somehow related to this, so added this"

EditorApplication.playModeStateChanged += (state) =>
{
    Debug.Log($"State changed {state} {Time.realtimeSinceStartup}");
};

And this is what I get in logs: image

eliatlas avatar May 13 '22 11:05 eliatlas

This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 7 days.

github-actions[bot] avatar Aug 12 '22 00:08 github-actions[bot]

Same here await UniTask.Delay(TimeSpan.FromSeconds(showTime), cancellationToken: token); Without token delay works fine, but not cancelling. With token delaying forever, if cancelled.

ReijiiNeko avatar Nov 01 '22 19:11 ReijiiNeko

any plans to fix it?

lvgrecords avatar Feb 23 '23 06:02 lvgrecords

Try

try
{
	await UniTask.Delay(delay, cancellationToken: _delayCancellation.Token);
}
catch (OperationCanceledException)
{

}

SergeyRomanko avatar Sep 26 '23 15:09 SergeyRomanko