CancellationToken 不适用于 WaitForConnectionAsync

CancellationToken not working with WaitForConnectionAsync

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

我希望最后一行在一秒钟后抛出一个 OperationCanceledException,但它永远挂起。为什么?

仅当您使用异步命名管道时才会检查取消令牌,这不是默认设置(是的,API 设计得非常糟糕)。要使其异步,您必须在 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();

然后取消令牌将按预期工作。