Skip to content

Commit 89e7051

Browse files
committed
Only use AsyncTestSyncContext when we know we're running an async void test
1 parent 8b49d99 commit 89e7051

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/xunit.v3.core/Sdk/v3/Runners/TestInvoker.cs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using System.ComponentModel;
33
using System.Linq;
44
using System.Reflection;
5+
using System.Runtime.CompilerServices;
56
using System.Security;
67
using System.Threading;
78
using System.Threading.Tasks;
@@ -410,11 +411,16 @@ public Task<decimal> RunAsync()
410411
protected virtual async Task InvokeTestMethodAsync(object? testClassInstance)
411412
{
412413
var oldSyncContext = SynchronizationContext.Current;
414+
var asyncSyncContext = default(AsyncTestSyncContext);
413415

414416
try
415417
{
416-
var asyncSyncContext = new AsyncTestSyncContext(oldSyncContext);
417-
SetSynchronizationContext(asyncSyncContext);
418+
// Only need the async test sync context when we know you have an "async void" method
419+
if (TestMethod.ReturnType == typeof(void) && TestMethod.GetCustomAttribute<AsyncStateMachineAttribute>() != null)
420+
{
421+
asyncSyncContext = new AsyncTestSyncContext(oldSyncContext);
422+
SetSynchronizationContext(asyncSyncContext);
423+
}
418424

419425
await Aggregator.RunAsync(
420426
() => Timer.AggregateAsync(
@@ -436,7 +442,7 @@ await Aggregator.RunAsync(
436442
var valueTask = GetValueTaskFromResult(result);
437443
if (valueTask.HasValue)
438444
await valueTask.Value;
439-
else
445+
else if (asyncSyncContext != null)
440446
{
441447
var ex = await asyncSyncContext.WaitForCompletionAsync();
442448
if (ex != null)

0 commit comments

Comments
 (0)