Files
PipeMethodCallsDemo/PipeServer/ServerMethods.cs
T
matt beb7086867 Refactor PipeClient to use ServerConnection wrapper and rename Server namespace
Introduce ServerConnection class in PipeClient to encapsulate server process
lifecycle, connection, restart, and cleanup instead of inline Process management.
Pass PipeClient<IPipeServerMethods> explicitly to example methods rather than
relying on a module-level field.

Rename namespace Server to PipeServer in PipeServer project and update
corresponding using directives.

Update error messages in ServerMethods to English.
2026-11-10 13:07:21 +01:00

60 lines
1.7 KiB
C#

using System.Collections.Concurrent;
using System.Numerics;
using PipeShared;
namespace PipeServer;
public class ServerMethods : IPipeServerMethods
{
public int Add(int a, int b) => a + b;
public Vector3 AddVector(Vector3 a, Vector3 b) => a + b;
public double Divide(double a, double b)
{
if (b == 0)
throw new DivideByZeroException("Division by 0 not allowed.");
return a / b;
}
public async Task<string> EchoAsync(string text)
{
await Task.Delay(50);
if (string.IsNullOrEmpty(text))
throw new ArgumentException("Text must not be empty.", nameof(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);
}