Skip to content

Conversation

bruno1308
Copy link

@bruno1308 bruno1308 commented Jan 23, 2025

Description

This pull request fixes an issue where RunSync(Func<Task>) might not restore the original SynchronizationContext after encountering an exception. The solution ensures the context is restored in a try/finally block so that Unity’s default context is never left in a corrupted state.

In my particular case, I had a bad glb file causing it to throw an exception during asset importing and making all my async tests fail (timeout) on my CI/CD setup since the SynchronizationContext was still ExclusiveSynchronizationContext when the tests started, caused by the exception that never restored Unity's default context.

Solution

  • Use a try/finally block so SynchronizationContext.SetSynchronizationContext(oldContext) always runs.
  • No functional changes otherwise.

It's worth noting that I've tried re-using the original finally clause, restoring the original context after (or before) sync.EndMessageLoop(), but that does not work since sync.EndMessageLoop() itself would trigger the context to switch back to ExclusiveSynchronizationContext regardless if I tried to do it before or after the call to sync.EndMessageLoop().

Before the fix

ExclusiveSynchronizationContext will be wrongly carried to the next asset as its oldContext as SynchronizationContext.SetSynchronizationContext(oldContext) is not called during an exception, making Unity's context to never be restored again in a headless CI/CD machine:

problem

After the fix

Unity context is restored after the exception:

fix

@unity-cla-assistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@atteneder
Copy link
Collaborator

Thanks for the PR. I'll review it hopefully next week.

@bruno1308
Copy link
Author

Hey @atteneder, have you had a chance to take a look at it?
We've been maintaining a fork with this change internally, but it would be great to have this in to get the future updates and use the official version.

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.

4 participants