Skip to content

Unexpected behavior with canceled CancellationToken passed to PipeWriter.FlushAsync #25633

@analogrelay

Description

@analogrelay

The program below never terminates. It's passing a canceled CancellationToken in to FlushAsync, catching the exception, and then completing the pipe. However, the ReadAsync call on the other end is never completed. If you comment out the cancellation, the pipe is completed properly and the ReadAsync completes. I wouldn't have expected the pipe to be un-completable after cancelling an action on it.

cc @pakrym @davidfowl

using System;
using System.IO.Pipelines;
using System.Threading;
using System.Threading.Tasks;

namespace PipeCancelFlushBlug
{
    class Program
    {
        static void Main(string[] args)
        {
            var pipe = new Pipe();

            var receiver = Receiver(pipe.Reader);
            var sender = Sender(pipe.Writer);

            Task.WaitAll(sender, receiver);
        }

        private static async Task Sender(PipeWriter pipeWriter)
        {
            var cts = new CancellationTokenSource();
            cts.Cancel(); // Comment this line out to fix everything.
            try
            {
                Console.WriteLine("Flushing");
                await pipeWriter.FlushAsync(cts.Token);
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Flush Cancelled");
            }
            finally
            {
                Console.WriteLine("Completing pipe");
                pipeWriter.Complete();
                Console.WriteLine("Completed pipe");
            }
        }

        private static async Task Receiver(PipeReader pipeReader)
        {
            Console.WriteLine("Reading...");
            var result = await pipeReader.ReadAsync();
            Console.WriteLine("Receiver complete");
        }
    }
}

cc @davidfowl @pakrym

Versions:

  • System.IO.Pipelines: 4.5.0-preview2-26313-01
  • SDK: 2.1.300-preview2-008367
  • .NET Core Runtime: 2.1.0-preview2-26313-01 (I realize these versions are exactly aligned

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions