private Task EndResponse() { var buffer = default(WritableBuffer); var hasBuffer = false; if (!HasStarted) { buffer = _output.Alloc(); WriteBeginResponseHeaders(ref buffer, ref _autoChunk); hasBuffer = true; } if (_autoChunk) { if (!hasBuffer) { buffer = _output.Alloc(); } WriteEndResponse(ref buffer); return(_output.WriteAsync(buffer)); } return(Task.CompletedTask); }
public async Task DuplexStreaming(IReadableChannel <GreetingRequest> requestStream, IWritableChannel <GreetingResponse> responseStream, MethodCallContext context) { Console.WriteLine("Received duplex streaming request from {{{0}}}", context); var greeting = "Hello!"; await responseStream.WriteAsync(new GreetingResponse { Greeting = greeting }).ConfigureAwait(false); Console.WriteLine("Sent: {0}", greeting); while (await requestStream.WaitReadAvailableAsync().ConfigureAwait(false)) { while (requestStream.TryRead(out var request)) { Console.WriteLine("Received: {0}", request.Name); greeting = $"Hello, {request.Name}!"; await responseStream .WriteAsync(new GreetingResponse { Greeting = greeting }) .ConfigureAwait(false); Console.WriteLine("Sent: {0}", greeting); } } Console.WriteLine("Request stream completed"); greeting = "Good Bye!"; await responseStream .WriteAsync(new GreetingResponse { Greeting = greeting }) .ConfigureAwait(false); Console.WriteLine("Sent: {0}", greeting); greeting = "See you again!"; await responseStream .WriteAsync(new GreetingResponse { Greeting = greeting }) .ConfigureAwait(false); Console.WriteLine("Sent: {0}", greeting); Console.WriteLine("Completed"); }
private static async Task CopyCompletedAsync(IReadableChannel input, IWritableChannel channel) { await input; do { var fin = input.Completion.IsCompleted; var inputBuffer = input.BeginRead(); try { if (inputBuffer.IsEmpty && fin) { return; } var buffer = channel.Alloc(); buffer.Append(inputBuffer); await channel.WriteAsync(buffer); } finally { input.EndRead(inputBuffer); } }while (input.IsCompleted); }
public static Task WriteAsync(this IWritableChannel channel, byte[] buffer, int offset, int count) { var writeBuffer = channel.Alloc(); writeBuffer.Write(buffer, offset, count); return(channel.WriteAsync(writeBuffer)); }
public static async Task CopyToAsync(this IReadableChannel input, IWritableChannel channel) { while (true) { await input; var fin = input.Completion.IsCompleted; var inputBuffer = input.BeginRead(); try { if (inputBuffer.IsEmpty && fin) { return; } var buffer = channel.Alloc(); buffer.Append(inputBuffer); await channel.WriteAsync(buffer); } finally { input.EndRead(inputBuffer); } } }
private static async Task WriteItems(IWritableChannel <int> channel, CancellationToken cancellationToken) { // Start generating items int counter = 0; while (!cancellationToken.IsCancellationRequested && counter < 5) { try { var value = counter++; Console.WriteLine($"Sending: {value}"); await channel.WriteAsync(value); Console.WriteLine("Waiting 0.5sec"); await Task.Delay(500); } catch (Exception ex) { Console.WriteLine($"Sender Threw: {ex}"); return; } } Console.WriteLine("Completing channel"); channel.Complete(); }
private static async Task Pipes_ReadWriteValues <T>(bool firstWaitToRead, int numItems, Func <int, T> getValue) { using (AnonymousPipeServerStream serverPipe = new AnonymousPipeServerStream(PipeDirection.Out)) using (AnonymousPipeClientStream clientPipe = new AnonymousPipeClientStream(PipeDirection.In, serverPipe.ClientSafePipeHandle)) { IWritableChannel <T> writer = Channel.WriteToStream <T>(serverPipe); IReadableChannel <T> reader = Channel.ReadFromStream <T>(clientPipe); for (int i = 0; i < numItems; i++) { T itemToWrite = getValue(i); Task <T> readItem = firstWaitToRead ? reader.WaitToReadAsync().ContinueWith(_ => reader.ReadAsync().AsTask()).Unwrap() : reader.ReadAsync().AsTask(); Task writeItem = writer.WriteAsync(itemToWrite); await Task.WhenAll(readItem, writeItem); Assert.Equal(itemToWrite, readItem.Result); } writer.Complete(); Assert.False(await reader.WaitToReadAsync()); await reader.Completion; } }
public static async Task CopyToAsync(this Stream stream, IWritableChannel channel) { while (true) { var buffer = channel.Alloc(2048); try { int bytesRead = await stream.ReadAsync(buffer.Memory.Array, buffer.Memory.Offset, buffer.Memory.Length); if (bytesRead == 0) { channel.CompleteWriting(); break; } else { buffer.UpdateWritten(bytesRead); await channel.WriteAsync(buffer); } } catch (Exception error) { channel.CompleteWriting(error); break; } } }
private static void Pipes_WaitForReadThenTryReadValues() { using (AnonymousPipeServerStream serverPipe = new AnonymousPipeServerStream(PipeDirection.Out)) using (AnonymousPipeClientStream clientPipe = new AnonymousPipeClientStream(PipeDirection.In, serverPipe.ClientSafePipeHandle)) { IWritableChannel <int> writer = Channel.WriteToStream <int>(serverPipe); IReadableChannel <int> reader = Channel.ReadFromStream <int>(clientPipe); Task.WaitAll( Task.Run(async() => { for (int i = 0; i < 100; i++) { await writer.WriteAsync(i); } writer.Complete(); Assert.False(writer.TryWrite(100)); }), Task.Run(async() => { int result; int i = 0; while (await reader.WaitToReadAsync()) { if (reader.TryRead(out result)) { Assert.Equal(i++, result); } } Assert.False(reader.TryRead(out result)); })); } }
private static void Pipes_EnumerateValues() { using (AnonymousPipeServerStream serverPipe = new AnonymousPipeServerStream(PipeDirection.Out)) using (AnonymousPipeClientStream clientPipe = new AnonymousPipeClientStream(PipeDirection.In, serverPipe.ClientSafePipeHandle)) { IWritableChannel <int> writer = Channel.WriteToStream <int>(serverPipe); IReadableChannel <int> reader = Channel.ReadFromStream <int>(clientPipe); Task.WaitAll( Task.Run(async() => { for (int i = 0; i < 100; i++) { await writer.WriteAsync(i); } writer.Complete(); Assert.False(writer.TryWrite(100)); }), Task.Run(async() => { int i = 0; IAsyncEnumerator <int> e = reader.GetAsyncEnumerator(); while (await e.MoveNextAsync()) { Assert.Equal(i++, e.Current); } })); } }
public void WriteToStream_Precancellation() { IWritableChannel <int> w = Channel.WriteToStream <int>(new MemoryStream()); var cts = new CancellationTokenSource(); cts.Cancel(); AssertSynchronouslyCanceled(w.WaitToWriteAsync(cts.Token), cts.Token); AssertSynchronouslyCanceled(w.WriteAsync(42, cts.Token), cts.Token); }
public async Task TryWrite_AfterComplete() { IWritableChannel <int> c = Channel.WriteToStream <int>(new MemoryStream()); Assert.True(c.TryComplete()); Assert.False(c.TryWrite(42)); AssertSynchronousFalse(c.WaitToWriteAsync()); await Assert.ThrowsAnyAsync <InvalidOperationException>(() => c.WriteAsync(42)); Assert.False(c.TryComplete()); }
public async Task ServerStreaming(GreetingRequest request, IWritableChannel <GreetingResponse> responseStream, MethodCallContext context) { Console.WriteLine("Received server streaming request from {{{0}}}", context); Console.WriteLine("Received: {0}", request.Name); var greeting = $"Hello, {request.Name}!"; await responseStream .WriteAsync(new GreetingResponse { Greeting = greeting }) .ConfigureAwait(false); Console.WriteLine("Sent: {0}", greeting); await Task.Delay(500).ConfigureAwait(false); greeting = $"Hello again, {request.Name}!"; await responseStream .WriteAsync(new GreetingResponse { Greeting = greeting }) .ConfigureAwait(false); Console.WriteLine("Sent: {0}", greeting); Console.WriteLine("Completed"); }
public static async Task WriteOrDisposeAsync <T>(this IWritableChannel <T> channel, T item, CancellationToken cancellationToken = default) where T : IDisposable { try { await channel.WriteAsync(item, cancellationToken).ConfigureAwait(false); } catch { item.Dispose(); throw; } }
private async Task SendAsync(ITransportChannelHeader header, Maybe <IPooledBuffer> body = default) { try { _log.Trace("Sending: {0} with body {1}", header, body); await _out.WriteAsync(new ChannelMessage(header, body)).ConfigureAwait(false); } catch { header.Dispose(); if (body.HasValue) { body.Value.Dispose(); } throw; } }
private static async Task WriteAsync <T>( IWritableChannel <T> channel, T arg, CancellationToken cancellationToken, TimeSpan sendTimeout) { using (var timeoutCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) { if (sendTimeout > TimeSpan.Zero) { // Cancel sending after timeout timeoutCancellation.CancelAfter(sendTimeout); } await channel.WriteAsync(arg, timeoutCancellation.Token).ConfigureAwait(false); } }
private static async Task PropagateAsync(IReadableChannel <TransportMessageFrame> channel1, IWritableChannel <TransportMessageFrame> channel2) { try { while (true) { var result = await channel1.TryReadAsync().ConfigureAwait(false); if (!result.HasValue) { break; } await channel2.WriteAsync(result.Value).ConfigureAwait(false); } channel2.TryComplete(); } catch (Exception ex) { channel2.TryTerminate(ex); } }
public async Task Execute(IReadableChannel input, IWritableChannel output) { while (true) { await input; var inputBuffer = input.BeginRead(); if (inputBuffer.IsEmpty && input.Completion.IsCompleted) { break; } var writerBuffer = output.Alloc(2048); var span = inputBuffer.FirstSpan; if (span.Length > 0) { _inflater.SetInput(span.BufferPtr, span.Length); int written = _inflater.Inflate(writerBuffer.Memory.BufferPtr, writerBuffer.Memory.Length); writerBuffer.UpdateWritten(written); var consumed = span.Length - _inflater.AvailableInput; inputBuffer = inputBuffer.Slice(0, consumed); } input.EndRead(inputBuffer); await output.WriteAsync(writerBuffer); } input.CompleteReading(); output.CompleteWriting(); _inflater.Dispose(); }
public async Task Execute(IReadableChannel input, IWritableChannel output) { while (true) { await input; var inputBuffer = input.BeginRead(); if (inputBuffer.IsEmpty && input.Completion.IsCompleted) { break; } var writerBuffer = output.Alloc(2048); var span = inputBuffer.FirstSpan; _deflater.SetInput(span.BufferPtr, span.Length); while (!_deflater.NeedsInput()) { int written = _deflater.ReadDeflateOutput(writerBuffer.Memory.BufferPtr, writerBuffer.Memory.Length); writerBuffer.UpdateWritten(written); } var consumed = span.Length - _deflater.AvailableInput; inputBuffer = inputBuffer.Slice(0, consumed); input.EndRead(inputBuffer); await output.WriteAsync(writerBuffer); } bool flushed; do { // Need to do more stuff here var writerBuffer = output.Alloc(2048); int compressedBytes; flushed = _deflater.Flush(writerBuffer.Memory.BufferPtr, writerBuffer.Memory.Length, out compressedBytes); writerBuffer.UpdateWritten(compressedBytes); await output.WriteAsync(writerBuffer); }while (flushed); bool finished; do { // Need to do more stuff here var writerBuffer = output.Alloc(2048); int compressedBytes; finished = _deflater.Finish(writerBuffer.Memory.BufferPtr, writerBuffer.Memory.Length, out compressedBytes); writerBuffer.UpdateWritten(compressedBytes); await output.WriteAsync(writerBuffer); }while (!finished); input.CompleteReading(); output.CompleteWriting(); _deflater.Dispose(); }
public static Task WriteAsync(this IWritableChannel channel, ArraySegment <byte> buffer) { return(channel.WriteAsync(buffer.Array, buffer.Offset, buffer.Count)); }
public override void Write(byte[] buffer, int offset, int count) { _output.WriteAsync(new Span <byte>(buffer, offset, count)).GetAwaiter().GetResult(); }
public void OnNext(T value) => _channel.WriteAsync(value).GetAwaiter().GetResult();