test(worker): net48-compatible timeout helper in the dispatcher gate test (WIP-010)

This commit is contained in:
Joseph Doherty
2026-12-03 10:07:29 -05:00
parent c30ba69a6d
commit eaa43cf42f
@@ -276,17 +276,19 @@ public sealed class StaCommandDispatcherTests
try
{
Task<MxCommandReply> first = await Task.Run(() => dispatcher.DispatchAsync(CreateCommand("correlation-1", MxCommandKind.Register)))
.WaitAsync(TimeSpan.FromSeconds(10));
// Task.Factory.StartNew (not Task.Run) so the returned reply task is not unwrapped: the
// dispatch call itself must return promptly even though the reply cannot complete yet.
Task<MxCommandReply> first = await WithTimeoutAsync(
Task.Factory.StartNew(() => dispatcher.DispatchAsync(CreateCommand("correlation-1", MxCommandKind.Register))));
Assert.True(entered.Wait(TimeSpan.FromSeconds(10)), "The command logger was never called.");
// The first command's log line is now blocked. Everything that takes the gate must still return.
Task<MxCommandReply> second = await Task.Run(() => dispatcher.DispatchAsync(CreateCommand("correlation-2", MxCommandKind.AddItem)))
.WaitAsync(TimeSpan.FromSeconds(10));
bool canceled = await Task.Run(() => dispatcher.CancelQueuedCommand("correlation-2"))
.WaitAsync(TimeSpan.FromSeconds(10));
int pending = await Task.Run(() => dispatcher.PendingCommandCount)
.WaitAsync(TimeSpan.FromSeconds(10));
Task<MxCommandReply> second = await WithTimeoutAsync(
Task.Factory.StartNew(() => dispatcher.DispatchAsync(CreateCommand("correlation-2", MxCommandKind.AddItem))));
bool canceled = await WithTimeoutAsync(
Task.Run(() => dispatcher.CancelQueuedCommand("correlation-2")));
int pending = await WithTimeoutAsync(
Task.Run(() => dispatcher.PendingCommandCount));
Assert.True(canceled);
Assert.Equal(0, pending);
@@ -297,7 +299,7 @@ public sealed class StaCommandDispatcherTests
release.Set();
}
Assert.Equal(ProtocolStatusCode.Ok, (await Task.Run(() => dispatcher.DispatchAsync(CreateCommand("correlation-3", MxCommandKind.Register)))).ProtocolStatus.Code);
Assert.Equal(ProtocolStatusCode.Ok, (await dispatcher.DispatchAsync(CreateCommand("correlation-3", MxCommandKind.Register))).ProtocolStatus.Code);
}
/// <summary>Verifies the opt-in environment value is parsed strictly.</summary>
@@ -347,6 +349,18 @@ public sealed class StaCommandDispatcherTests
/// <summary>
/// Test executor that records executed command correlations and thread IDs.
/// </summary>
// net48 has no Task.WaitAsync; a task that does not finish in time fails the test instead of hanging it.
private static async Task<T> WithTimeoutAsync<T>(Task<T> task)
{
Task finished = await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(10)));
if (!ReferenceEquals(finished, task))
{
throw new TimeoutException("The operation did not complete while the command logger was blocked.");
}
return await task;
}
private sealed class BlockingWorkerLogger : IWorkerLogger
{
private readonly ManualResetEventSlim entered;