Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 233
wezten Avatar asked Dec 09 '18 18:12

wezten


1 Answers

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.

like image 167
Kevin Gosse Avatar answered Oct 31 '22 11:10

Kevin Gosse