Skip to content

RunOnThreadPool: cancelling at the wrong time prevents returning to the main thread #669

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Tomcc
Copy link

@Tomcc Tomcc commented Jul 10, 2025

Hi! My game's test suite was hitting a ton of random failures to return to the main thread (which in turn caused Unity exceptions), and I think I traced it down to UniTask itself.

UniTask.RunOnThreadPool (all versions) currently looks like this:

        public static async UniTask RunOnThreadPool(Action<object> action, object state, bool configureAwait = true, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            await UniTask.SwitchToThreadPool();

            cancellationToken.ThrowIfCancellationRequested();

            if (configureAwait)
            {
                try
                {
                    action(state);
                }
                finally
                {
                    await UniTask.Yield();
                }
            }
            else
            {
                action(state);
            }

            cancellationToken.ThrowIfCancellationRequested();
        }

if the timing aligns just right, the second cancellationToken.ThrowIfCancellationRequested(); will throw an exception on the threadpool and prevent UniTask.Yield() from ever running.
If the caller handles cancellations or has its own finally's, everything after this will run on the wrong thread.

I made a pretty simple change that moves the cancellation check inside the try itself.

Some versions of RunOnThreadPool had a cancellationToken.ThrowIfCancellationRequested(); inside the finally before the Yield which would cause the same problem, so I removed those as well.

Thanks for the great library btw!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant