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:
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user