From 04e94edd642fdb0e8d56f805cbe6398cabc9b2df Mon Sep 17 00:00:00 2001 From: Matthias Heil Date: Tue, 10 Nov 2026 10:16:24 +0100 Subject: [PATCH] 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. --- Client/Program.cs | 141 ++++++++++++++++++++++++++++-------------- Server/Calculator.cs | 31 ++++++++++ Shared/ICalculator.cs | 2 + 3 files changed, 128 insertions(+), 46 deletions(-) diff --git a/Client/Program.cs b/Client/Program.cs index cb82c2d..c688b0b 100644 --- a/Client/Program.cs +++ b/Client/Program.cs @@ -1,41 +1,51 @@ -using System.Diagnostics; +using System.Diagnostics; using PipeMethodCalls; using ClientServerShared; Console.WriteLine("Client started."); -const string pipeName = "PipeDemo"; +// Unique pipe name per client run, so multiple clients/servers do not interfere +string pipeName = $"PipeDemo-{Environment.ProcessId}-{Guid.NewGuid():N}"; Process? serverProcess = null; -PipeClient client = new(new JsonFieldsPipeSerializer(), pipeName); +PipeClient client = null!; try { - // Check whether a server is already running by trying a short connect - try - { - using var probeCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(500)); - await client.ConnectAsync(probeCts.Token); - Console.WriteLine("Server already running."); - } - catch (Exception ex) when (ex is OperationCanceledException or TimeoutException) - { - client.Dispose(); - Console.WriteLine("No server running. Starting server..."); - serverProcess = StartServer(pipeName); - serverProcess.EnableRaisingEvents = true; - serverProcess.Exited += (_, _) => - { - if (serverProcess.ExitCode != 0) - Console.WriteLine($"Server process exited abnormally (exit code {serverProcess.ExitCode})."); - }; - - client = new PipeClient(new JsonFieldsPipeSerializer(), pipeName); - using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - await client.ConnectAsync(cts.Token); - } + Console.WriteLine($"Starting server on pipe {pipeName}..."); + await StartServerAndConnectAsync(pipeName); Console.WriteLine("Connected to server."); + await BasicCallsExampleAsync(); + await ServerExceptionsExampleAsync(); + await CancellationExampleAsync(); + await KillOnTimeoutExampleAsync(); + await CrashExampleAsync(); +} +catch (Exception ex) when (ex is not PipeInvokeFailedException) +{ + // Communication failed: check whether the server process died + if (serverProcess is not null && serverProcess.WaitForExit(2000)) + Console.WriteLine($"Connection lost, server terminated with exit code {serverProcess.ExitCode}: {ex.GetType().Name}: {ex.Message}"); + else + Console.WriteLine($"Communication error: {ex.GetType().Name}: {ex.Message}"); +} +finally +{ + // Disposing the client closes the pipe, the server then exits. + client?.Dispose(); + if (serverProcess is not null) + { + if (!serverProcess.WaitForExit(5000)) + serverProcess.Kill(); + serverProcess.Dispose(); + } +} + +Console.WriteLine("Client finished."); + +async Task BasicCallsExampleAsync() +{ int sum = await client.InvokeAsync(c => c.Add(2, 3)); Console.WriteLine($"Add(2, 3) = {sum}"); @@ -47,8 +57,11 @@ try string echo = await client.InvokeAsync(c => c.EchoAsync("Hallo")); Console.WriteLine(echo); +} - // Server-side exceptions are forwarded to the client +// Server-side exceptions are forwarded to the client +async Task ServerExceptionsExampleAsync() +{ try { await client.InvokeAsync(c => c.Divide(1, 0)); @@ -66,31 +79,67 @@ try { Console.WriteLine($"Server exception (Echo): {ex.Message}"); } +} - // Simulate a server crash - await client.InvokeAsync(c => c.Crash(42)); -} -catch (Exception ex) when (ex is not PipeInvokeFailedException) +// InvokeAsync with a CancellationToken: the client stops waiting when the token is canceled. +// PipeMethodCalls does not propagate cancellation to the server, so an explicit +// CancelOperation call with the operation id stops the server-side work as well. +async Task CancellationExampleAsync() { - // Communication failed: check whether the server process died - if (serverProcess is not null && serverProcess.WaitForExit(2000)) - Console.WriteLine($"Connection lost, server terminated with exit code {serverProcess.ExitCode}: {ex.GetType().Name}: {ex.Message}"); - else - Console.WriteLine($"Communication error: {ex.GetType().Name}: {ex.Message}"); -} -finally -{ - // Disposing the client closes the pipe, the server then exits. - client.Dispose(); - if (serverProcess is not null) + using var invokeCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); + var operationId = Guid.NewGuid(); + try { - if (!serverProcess.WaitForExit(5000)) - serverProcess.Kill(); - serverProcess.Dispose(); + int result = await client.InvokeAsync(c => c.SlowOperationAsync(2000, operationId), invokeCts.Token); + Console.WriteLine($"SlowOperationAsync = {result}"); + } + catch (OperationCanceledException) + { + await client.InvokeAsync(c => c.CancelOperation(operationId)); + Console.WriteLine("SlowOperationAsync canceled after 200 ms."); } } -Console.WriteLine("Client finished."); +// Kill the server process if it does not respond in time, then restart it +async Task KillOnTimeoutExampleAsync() +{ + using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(1)); + try + { + await client.InvokeAsync(c => c.SlowOperationAsync(30_000, Guid.NewGuid()), timeoutCts.Token); + } + catch (OperationCanceledException) when (serverProcess is not null) + { + Console.WriteLine("Server did not respond within 1 s. Killing server process..."); + serverProcess.Kill(entireProcessTree: true); + await serverProcess.WaitForExitAsync(); + serverProcess.Dispose(); + client.Dispose(); + + Console.WriteLine("Restarting server..."); + await StartServerAndConnectAsync(pipeName); + Console.WriteLine("Reconnected to server."); + } +} + +// Simulate a server crash +async Task CrashExampleAsync() => await client.InvokeAsync(c => c.Crash(42)); + +async Task StartServerAndConnectAsync(string pipeName) +{ + var process = StartServer(pipeName); + process.EnableRaisingEvents = true; + process.Exited += (_, _) => + { + if (process.ExitCode != 0) + Console.WriteLine($"Server process exited abnormally (exit code {process.ExitCode})."); + }; + serverProcess = process; + + client = new PipeClient(new JsonFieldsPipeSerializer(), pipeName); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await client.ConnectAsync(cts.Token); +} // Start server process (Server is referenced, so its output is copied next to the client). static Process StartServer(string pipeName) diff --git a/Server/Calculator.cs b/Server/Calculator.cs index f184fa3..2ae8928 100644 --- a/Server/Calculator.cs +++ b/Server/Calculator.cs @@ -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 RunningOperations = new(); + + public async Task 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); } diff --git a/Shared/ICalculator.cs b/Shared/ICalculator.cs index cd322f2..a8c547c 100644 --- a/Shared/ICalculator.cs +++ b/Shared/ICalculator.cs @@ -8,6 +8,8 @@ public interface ICalculator Vector3 AddVector(Vector3 a, Vector3 b); double Divide(double a, double b); Task EchoAsync(string text); + Task SlowOperationAsync(int delayMs, Guid operationId); + void CancelOperation(Guid operationId); void Crash(int exitCode); }