Fix Synchronization Context not resetting after exception #29
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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
SynchronizationContext.SetSynchronizationContext(oldContext)
always runs.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 sincesync.EndMessageLoop()
itself would trigger the context to switch back toExclusiveSynchronizationContext
regardless if I tried to do it before or after the call tosync.EndMessageLoop()
.Before the fix
ExclusiveSynchronizationContext
will be wrongly carried to the next asset as itsoldContext
asSynchronizationContext.SetSynchronizationContext(oldContext)
is not called during an exception, making Unity's context to never be restored again in a headless CI/CD machine:After the fix
Unity context is restored after the exception: