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:
+97
-48
@@ -1,41 +1,51 @@
|
|||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using PipeMethodCalls;
|
using PipeMethodCalls;
|
||||||
using ClientServerShared;
|
using ClientServerShared;
|
||||||
|
|
||||||
Console.WriteLine("Client started.");
|
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;
|
Process? serverProcess = null;
|
||||||
PipeClient<ICalculator> client = new(new JsonFieldsPipeSerializer(), pipeName);
|
PipeClient<ICalculator> client = null!;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// Check whether a server is already running by trying a short connect
|
Console.WriteLine($"Starting server on pipe {pipeName}...");
|
||||||
try
|
await StartServerAndConnectAsync(pipeName);
|
||||||
{
|
|
||||||
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("Connected to server.");
|
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));
|
int sum = await client.InvokeAsync(c => c.Add(2, 3));
|
||||||
Console.WriteLine($"Add(2, 3) = {sum}");
|
Console.WriteLine($"Add(2, 3) = {sum}");
|
||||||
|
|
||||||
@@ -47,8 +57,11 @@ try
|
|||||||
|
|
||||||
string echo = await client.InvokeAsync(c => c.EchoAsync("Hallo"));
|
string echo = await client.InvokeAsync(c => c.EchoAsync("Hallo"));
|
||||||
Console.WriteLine(echo);
|
Console.WriteLine(echo);
|
||||||
|
}
|
||||||
|
|
||||||
// Server-side exceptions are forwarded to the client
|
// Server-side exceptions are forwarded to the client
|
||||||
|
async Task ServerExceptionsExampleAsync()
|
||||||
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await client.InvokeAsync(c => c.Divide(1, 0));
|
await client.InvokeAsync(c => c.Divide(1, 0));
|
||||||
@@ -66,31 +79,67 @@ try
|
|||||||
{
|
{
|
||||||
Console.WriteLine($"Server exception (Echo): {ex.Message}");
|
Console.WriteLine($"Server exception (Echo): {ex.Message}");
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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()
|
||||||
|
{
|
||||||
|
using var invokeCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
|
||||||
|
var operationId = Guid.NewGuid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
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.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
// Simulate a server crash
|
||||||
await client.InvokeAsync(c => c.Crash(42));
|
async Task CrashExampleAsync() => await client.InvokeAsync(c => c.Crash(42));
|
||||||
}
|
|
||||||
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 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).
|
// Start server process (Server is referenced, so its output is copied next to the client).
|
||||||
static Process StartServer(string pipeName)
|
static Process StartServer(string pipeName)
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
using System.Numerics;
|
using System.Numerics;
|
||||||
using ClientServerShared;
|
using ClientServerShared;
|
||||||
|
|
||||||
@@ -24,5 +25,35 @@ public class Calculator : ICalculator
|
|||||||
return $"Echo: {text}";
|
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);
|
public void Crash(int exitCode) => Environment.Exit(exitCode);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ public interface ICalculator
|
|||||||
Vector3 AddVector(Vector3 a, Vector3 b);
|
Vector3 AddVector(Vector3 a, Vector3 b);
|
||||||
double Divide(double a, double b);
|
double Divide(double a, double b);
|
||||||
Task<string> EchoAsync(string text);
|
Task<string> EchoAsync(string text);
|
||||||
|
Task<int> SlowOperationAsync(int delayMs, Guid operationId);
|
||||||
|
void CancelOperation(Guid operationId);
|
||||||
void Crash(int exitCode);
|
void Crash(int exitCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user