Search code examples
c#asynchronousnamed-pipes

CancellationToken not working with WaitForConnectionAsync


NamedPipeServerStream server=new NamedPipeServerStream("aaqq");
var ct=new CancellationTokenSource();
ct.CancelAfter(1000);
server.WaitForConnectionAsync(ct.Token).Wait();

I would expect the last line to throw an OperationCanceledException after a second, but instead it hangs forever. Why?


Solution

  • The cancellation token is checked only if you're using an asynchronous namedpipe, which isn't the default (yup, the API is really poorly designed). To make it asynchronous, you have to provide the right value in PipeOptions:

    NamedPipeServerStream server = new NamedPipeServerStream("aaqq", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
    var ct = new CancellationTokenSource();
    ct.CancelAfter(1000);
    server.WaitForConnectionAsync(ct.Token).Wait();
    

    Then the cancellation token will work as expected.