Issue
Our code is relying on a third-party library which posts some action to be executed on the SynchronizationContext.Current, this breaks some tests that require Apartment(ApartmentState.STA) and return async Task.
We managed to strip down the problem to the following tests (one is failing while the other is not).
Tested with NUnit console 3.10.0 and NUnit framework 3.11.0
Failing test
[Test]
[Apartment(ApartmentState.STA)]
public async Task FailingTest()
{
SynchronizationContext.Current.Post(state => { }, null);
await Task.CompletedTask;
}
❗️ Exception
System.InvalidOperationException : Shutting down SingleThreadedTestSynchronizationContext with work still in the queue.
in NUnit.Framework.Internal.SingleThreadedTestSynchronizationContext.ShutDown() in C:\src\nunit\nunit\src\NUnitFramework\framework\Internal\SingleThreadedSynchronizationContext.cs:riga 90
in NUnit.Framework.Internal.AsyncToSyncAdapter.<>c__DisplayClass10_1.<InitializeExecutionEnvironment>b__0() in C:\src\nunit\nunit\src\NUnitFramework\framework\Internal\AsyncToSyncAdapter.cs:riga 128
in NUnit.Framework.Internal.AsyncToSyncAdapter.Await(Func`1 invoke) in C:\src\nunit\nunit\src\NUnitFramework\framework\Internal\AsyncToSyncAdapter.cs:riga 88
in NUnit.Framework.Internal.Commands.TestMethodCommand.RunTestMethod(TestExecutionContext context) in C:\src\nunit\nunit\src\NUnitFramework\framework\Internal\Commands\TestMethodCommand.cs:riga 84
Passing test
[Test]
[Apartment(ApartmentState.STA)]
public async Task SuccessfulTest()
{
SynchronizationContext.Current.Post(state => { }, null);
await Task.Yield();
}
Comments
We understood that Task.Yield() will force a context switch allowing for the synchronization context queue to be processed, while Task.Result won't. After having a look at the code and issues we saw that this is linked to #2818 and #2774
Issue
Our code is relying on a third-party library which posts some action to be executed on the
SynchronizationContext.Current, this breaks some tests that requireApartment(ApartmentState.STA)and returnasync Task.We managed to strip down the problem to the following tests (one is failing while the other is not).
Tested with NUnit console 3.10.0 and NUnit framework 3.11.0
Failing test
❗️ Exception
Passing test
Comments
We understood that
Task.Yield()will force a context switch allowing for the synchronization context queue to be processed, whileTask.Resultwon't. After having a look at the code and issues we saw that this is linked to #2818 and #2774