HttpClient Request Cancellation - Why is TaskCanceledException.CancellationToken.IsCancellationRequested false?

Given the following code:

var cts = new CancellationTokenSource(); try { // get a "hot" task var task = new HttpClient().GetAsync("http://www.google.com", cts.Token); // request cancellation cts.Cancel(); await task; // pass: Assert.Fail("expected TaskCanceledException to be 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 to exception"); } 

I would expect ex.CancellationToken.IsCancellationRequested be true inside the catch block, but it is not. I do not understand something?

+23
c # async-await cancellationtokensource
Mar 28 '15 at 15:44
source share
1 answer

In this case, since the HttpClient inside (in SendAsync ) uses TaskCompletionSource to represent the async operation. It returns TaskCompletionSource.Task and that the await task is included.

Then it calls base.SendAsync and registers the continuation in the returned task, which accordingly cancels / completes / calls the TaskCompletionSource task.

In case of cancellation, TaskCompletionSource.TrySetCanceled used, which associates the canceled task with the new CancellationToken ( default(CancellationToken) ).

This can be seen by looking at TaskCanceledException . At the top of ex.CancellationToken.IsCancellationRequested is false ex.CancellationToken.CanBeCanceled also false , which means that this CancellationToken can never be canceled, since it was not created using the CancellationTokenSource .




IMO should use TaskCompletionSource.TrySetCanceled(CancellationToken) . Thus, the TaskCompletionSource will be associated with the CancellationToken passed by the consumer, and not just the default CancellationToken . I think this is a bug (albeit a small one), and I sent a connection question about this.

+35
Mar 28 '15 at 16:04
source



All Articles