Closed james-world closed 2 years ago
Tagging subscribers to this area: @eerhardt, @maryamariyan See info in area-owners.md if you want to be subscribed.
Author: | james-world |
---|---|
Assignees: | - |
Labels: | `untriaged`, `area-Extensions-Hosting` |
Milestone: | - |
Task.FromCanceled requires that the CancellationToken passed to it has had cancellation requested, i.e. its IsCancellationRequested returns true. I assume in your test, the code calling ExecuteAsync cancels the token immediately after ExecuteAsync synchronously returns, which would explain why the original snippet always fails (it's calling FromCanceled with a non-canceled token) and why the latter non-deterministically but almost always succeeds (because the token has had cancellation requested by the time you call FromCanceled).
OK - I misunderstood what Task.FromCanceled is for (note to self, read the intellisense!). Adding the Task.Yield just caused the exception to occur on a background thread, so I missed it. Doh! It would be nice to have an easier wait to await cancellation though. It seems you have to do a lot of boiler plate to do this.
It would be nice to have an easier wait to await cancellation though
Do you mean you want to await for a cancellation request? If nothing else, you can do:
await Task.Delay(-1, cancellationToken);
Description
If I do this in my BackgroundService (.NET 5.0)
I get this:
But if I do this:
All is well. Which seems plain wrong to me.
It's not an uncommon pattern either where you want to do something like:
Configuration
.NET 5.0, SDK 5.0.401
Related to https://github.com/dotnet/runtime/issues/36063 possibly.