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
+95 -46
View File
@@ -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<ICalculator> client = new(new JsonFieldsPipeSerializer(), pipeName);
PipeClient<ICalculator> 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<ICalculator>(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<ICalculator>(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)