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
to be true
inside the catch block, but it is not. Am I misunderstanding something?
ex.CancelationToken
instance equal (ReferenceEqual) to cts? Documentation states: "If the token is associated with a canceled operation, theCancellationToken.IsCancellationRequested
property of the token returnstrue
". – AlexCancellationToken
is a struct, soReferenceEquals()
will always return false. – Peter DunihoCancellationToken token = cts.Token;
and evaluateobject.ReferenceEquals(token, token)
(i.e. compare theCancellationToken
value to itself), even that will returnfalse
, because value types have to be boxed before being passed as anobject
reference, and so the boxed objects will always be different, even if they were obtained from the same value. – Peter DunihoMain()
can't beasync
) and it behaves exactly as reported. – Peter Duniho