Compare commits

..
2 Commits
Author SHA1 Message Date
Matthias Heil 8fbb2e2e46 Log client execution to XML report
Replace console output with synchronized XML logging, including
timestamps, startup and shutdown events, errors, cancellations,
timeouts, restarts, and abnormal server exits. Save the completed
report as `ClientReport.xml` in the executable directory.
2026-11-10 10:20:18 +01:00
Matthias Heil 04e94edd64 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.
2026-11-10 10:16:24 +01:00
3 changed files with 161 additions and 65 deletions
+128 -65
View File
@@ -1,87 +1,44 @@
using System.Diagnostics; using System.Diagnostics;
using System.Xml.Linq;
using PipeMethodCalls; using PipeMethodCalls;
using ClientServerShared; using ClientServerShared;
Console.WriteLine("Client started."); // All output is written to an XML report next to the executable
string reportPath = Path.Combine(AppContext.BaseDirectory, "ClientReport.xml");
var report = new XElement("Report", new XAttribute("Started", DateTime.Now.ToString("O")));
const string pipeName = "PipeDemo"; Log("Client started.");
// 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 Log($"Starting server on pipe {pipeName}...");
try await StartServerAndConnectAsync(pipeName);
{ Log("Connected to server.");
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); await BasicCallsExampleAsync();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); await ServerExceptionsExampleAsync();
await client.ConnectAsync(cts.Token); await CancellationExampleAsync();
} await KillOnTimeoutExampleAsync();
Console.WriteLine("Connected to server."); await CrashExampleAsync();
int sum = await client.InvokeAsync(c => c.Add(2, 3));
Console.WriteLine($"Add(2, 3) = {sum}");
var vector = await client.InvokeAsync(c => c.AddVector(new System.Numerics.Vector3(1, 2, 3), new System.Numerics.Vector3(4, 5, 6)));
Console.WriteLine($"AddVector((1,2,3), (4,5,6)) = {vector}");
double quotient = await client.InvokeAsync(c => c.Divide(10, 4));
Console.WriteLine($"Divide(10, 4) = {quotient}");
string echo = await client.InvokeAsync(c => c.EchoAsync("Hallo"));
Console.WriteLine(echo);
// Server-side exceptions are forwarded to the client
try
{
await client.InvokeAsync(c => c.Divide(1, 0));
}
catch (PipeInvokeFailedException ex)
{
Console.WriteLine($"Server exception (Divide): {ex.Message}");
}
try
{
await client.InvokeAsync(c => c.EchoAsync(""));
}
catch (PipeInvokeFailedException ex)
{
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) catch (Exception ex) when (ex is not PipeInvokeFailedException)
{ {
// Communication failed: check whether the server process died // Communication failed: check whether the server process died
if (serverProcess is not null && serverProcess.WaitForExit(2000)) if (serverProcess is not null && serverProcess.WaitForExit(2000))
Console.WriteLine($"Connection lost, server terminated with exit code {serverProcess.ExitCode}: {ex.GetType().Name}: {ex.Message}"); Log($"Connection lost, server terminated with exit code {serverProcess.ExitCode}: {ex.GetType().Name}: {ex.Message}");
else else
Console.WriteLine($"Communication error: {ex.GetType().Name}: {ex.Message}"); Log($"Communication error: {ex.GetType().Name}: {ex.Message}");
} }
finally finally
{ {
// Disposing the client closes the pipe, the server then exits. // Disposing the client closes the pipe, the server then exits.
client.Dispose(); client?.Dispose();
if (serverProcess is not null) if (serverProcess is not null)
{ {
if (!serverProcess.WaitForExit(5000)) if (!serverProcess.WaitForExit(5000))
@@ -90,7 +47,113 @@ finally
} }
} }
Console.WriteLine("Client finished."); Log("Client finished.");
lock (report)
new XDocument(report).Save(reportPath);
// Thread-safe: also called from the Process.Exited event
void Log(string message)
{
lock (report)
report.Add(new XElement("Entry", new XAttribute("Time", DateTime.Now.ToString("O")), message));
}
async Task BasicCallsExampleAsync()
{
int sum = await client.InvokeAsync(c => c.Add(2, 3));
Log($"Add(2, 3) = {sum}");
var vector = await client.InvokeAsync(c => c.AddVector(new System.Numerics.Vector3(1, 2, 3), new System.Numerics.Vector3(4, 5, 6)));
Log($"AddVector((1,2,3), (4,5,6)) = {vector}");
double quotient = await client.InvokeAsync(c => c.Divide(10, 4));
Log($"Divide(10, 4) = {quotient}");
string echo = await client.InvokeAsync(c => c.EchoAsync("Hallo"));
Log(echo);
}
// Server-side exceptions are forwarded to the client
async Task ServerExceptionsExampleAsync()
{
try
{
await client.InvokeAsync(c => c.Divide(1, 0));
}
catch (PipeInvokeFailedException ex)
{
Log($"Server exception (Divide): {ex.Message}");
}
try
{
await client.InvokeAsync(c => c.EchoAsync(""));
}
catch (PipeInvokeFailedException ex)
{
Log($"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);
Log($"SlowOperationAsync = {result}");
}
catch (OperationCanceledException)
{
await client.InvokeAsync(c => c.CancelOperation(operationId));
Log("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)
{
Log("Server did not respond within 1 s. Killing server process...");
serverProcess.Kill(entireProcessTree: true);
await serverProcess.WaitForExitAsync();
serverProcess.Dispose();
client.Dispose();
Log("Restarting server...");
await StartServerAndConnectAsync(pipeName);
Log("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)
Log($"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)
+31
View File
@@ -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);
} }
+2
View File
@@ -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);
} }