c# - Cancelling an HttpClient Request - Why is TaskCanceledException.CancellationToken.IsCancellationRequested false? -
given following code:
var cts = new cancellationtokensource(); try { // "hot" task var task = new httpclient().getasync("http://www.google.com", cts.token); // request cancellation cts.cancel(); await task; // pass: assert.fail("expected taskcanceledexception thrown"); } catch (taskcanceledexception ex) { // pass: assert.istrue(cts.token.iscancellationrequested, "expected cancellation requested on original token"); // fail: assert.istrue(ex.cancellationtoken.iscancellationrequested, "expected cancellation requested on token attached exception"); } i expect ex.cancellationtoken.iscancellationrequested true inside catch block, not. misunderstanding something?
that's case because httpclient internally (in sendasync) using taskcompletionsource represent async operation. returns taskcompletionsource.task , that's task await on.
it calls base.sendasync , registers continuation on returned task cancels/completes/faults taskcompletionsource's task accordingly.
in case of cancellation uses taskcompletionsource.trysetcanceled associates canceled task new cancellationtoken (default(cancellationtoken)).
you can see looking @ taskcanceledexception. on top of ex.cancellationtoken.iscancellationrequested being false ex.cancellationtoken.canbecanceled false, meaning cancellationtoken can never canceled wasn't created using cancellationtokensource.
imo should using taskcompletionsource.trysetcanceled(cancellationtoken) instead. way taskcompletionsource associated cancellationtoken passed in consumer , not default cancellationtoken. think it's bug (though minor one) , submitted issue on connect it.
Comments
Post a Comment