コード例 #1
0
        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);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: stjordanis/plexus-interop
        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");
        }
コード例 #3
0
        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);
        }
コード例 #4
0
        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));
        }
コード例 #5
0
        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);
                }
            }
        }
コード例 #6
0
        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();
        }
コード例 #7
0
        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;
                }
        }
コード例 #8
0
        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;
                }
            }
        }
コード例 #9
0
        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));
                    }));
                }
        }
コード例 #10
0
        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);
                        }
                    }));
                }
        }
コード例 #11
0
        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);
        }
コード例 #12
0
        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());
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: stjordanis/plexus-interop
        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");
        }
コード例 #14
0
 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;
     }
 }
コード例 #15
0
 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;
     }
 }
コード例 #16
0
        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);
            }
        }
コード例 #17
0
        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);
            }
        }
コード例 #18
0
            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();
            }
コード例 #19
0
            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();
            }
コード例 #20
0
 public static Task WriteAsync(this IWritableChannel channel, ArraySegment <byte> buffer)
 {
     return(channel.WriteAsync(buffer.Array, buffer.Offset, buffer.Count));
 }
コード例 #21
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     _output.WriteAsync(new Span <byte>(buffer, offset, count)).GetAwaiter().GetResult();
 }
コード例 #22
0
 public void OnNext(T value) => _channel.WriteAsync(value).GetAwaiter().GetResult();