Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 12 additions & 41 deletions test/EFCore.Relational.Tests/RelationalConnectionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1095,52 +1095,23 @@ public void HandleTransactionCompleted_with_concurrent_ClearTransactions_is_thre
var connection = new FakeRelationalConnection(
CreateOptions(new FakeRelationalOptionsExtension().WithConnectionString("Database=ConcurrencyTest")));

using var scope = new TransactionScope();
connection.Open();

var random = new Random();
var resetFirst = random.Next(0, 1) == 0;
var tasks = new Task[2];
tasks[0] = Task.Run(async () =>
using (var scope = new TransactionScope())
{
try
{
// Small delay to increase chance of race condition
await Task.Yield();

if (resetFirst)
{
((IResettableService)connection).ResetState();
}
else
{
scope.Complete();
}
}
catch (Exception ex)
{
lock (exceptions)
{
exceptions.Add(ex);
}
}
});
connection.Open();
scope.Complete();
}
// At this point, the TransactionCompleted event might be about to fire on a background thread

tasks[1] = Task.Run(async () =>
// Now test the race between the event handler and ClearTransactions
var task = Task.Run(async () =>
{
try
{
// Small delay to increase chance of race condition
await Task.Yield();
// Small delay to allow TransactionCompleted event to potentially fire
await Task.Delay(1);

if (resetFirst)
{
scope.Complete();
}
else
{
((IResettableService)connection).ResetState();
}
// ResetState calls ClearTransactions which might race with HandleTransactionCompleted
((IResettableService)connection).ResetState();
}
catch (Exception ex)
{
Expand All @@ -1151,7 +1122,7 @@ public void HandleTransactionCompleted_with_concurrent_ClearTransactions_is_thre
}
});

Task.WaitAll(tasks, TimeSpan.FromSeconds(10));
Task.WaitAll(new[] { task }, TimeSpan.FromSeconds(10));
}

Assert.Empty(exceptions);
Expand Down