public static async Task WriteAsync <T>(this IWritableChannel <T> channel, T item, CancellationToken cancellationToken = default) { var result = await channel.TryWriteAsync(item, cancellationToken).ConfigureAwait(false); if (!result) { throw new OperationCanceledException(); } }
// Implementation of server streaming method GetRateStream public async Task GetRateStream( CcyPair request, IWritableChannel <CcyPairRate> responseStream, MethodCallContext context) { Console.WriteLine("Received subscription: {0}", request); try { do { var response = GetCcyPairRate(request); Console.WriteLine("Sending response: {0}", response); await responseStream.TryWriteAsync(response, context.CancellationToken); await Task.Delay(_random.Next(1000, 3000), context.CancellationToken); } while (!context.CancellationToken.IsCancellationRequested); } catch (OperationCanceledException) when(context.CancellationToken.IsCancellationRequested) { // Ignoring cancellation exception } Console.WriteLine("Subscription completed"); }