Harden client/server IPC and cancellation

Use a dedicated server per client run with unique pipes, automatic
failure recovery and reconnection, and robust resource cleanup. Add
cancellation and timeout support to calculator operations, plus demos
covering exceptions, cancellation, timeouts, and server crashes.
This commit is contained in:
Matthias Heil
2026-11-10 10:16:24 +01:00
parent 06763d6c15
commit 04e94edd64
3 changed files with 128 additions and 46 deletions
+31
View File
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Numerics;
using ClientServerShared;
@@ -24,5 +25,35 @@ public class Calculator : ICalculator
return $"Echo: {text}";
}
// Shared across instances: the handler factory may create a new Calculator per call.
private static readonly ConcurrentDictionary<Guid, CancellationTokenSource> RunningOperations = new();
public async Task<int> SlowOperationAsync(int delayMs, Guid operationId)
{
using var cts = new CancellationTokenSource();
if (!RunningOperations.TryAdd(operationId, cts))
throw new InvalidOperationException($"Operation {operationId} is already running.");
try
{
await Task.Delay(delayMs, cts.Token);
return delayMs;
}
catch (OperationCanceledException)
{
Console.WriteLine($"SlowOperationAsync {operationId} canceled by client.");
throw;
}
finally
{
RunningOperations.TryRemove(operationId, out _);
}
}
public void CancelOperation(Guid operationId)
{
if (RunningOperations.TryGetValue(operationId, out var cts))
cts.Cancel();
}
public void Crash(int exitCode) => Environment.Exit(exitCode);
}