Skip to content

Task Cancelled By Manually-Thrown OperationCancelledException #24848

@bgribaudo

Description

@bgribaudo

According to .Net Standard's documentation for Task.IsCancelled, there are three conditions when a task will report that it was cancelled. However, I'm observing cancelled tasks caused by a fourth condition. :-)

I'm trying to figure out whether what I'm observing is a bug with .Net or a case of incomplete documentation. :-)

Documentation

According to the docs, the three reasons a task may complete as cancelled are:

  • Its CancellationToken was marked for cancellation before the task started executing,
  • The task acknowledged the cancellation request on its already signaled CancellationToken by throwing an OperationCanceledException that bears the same CancellationToken.
  • The task acknowledged the cancellation request on its already signaled CancellationToken by calling the ThrowIfCancellationRequested method on the CancellationToken.

All of these require that the Task is associated with a CancellationToken.

What I'm Seeing

Manually throwing an OperationCancelledException that is unassociated with a CancellationToken also results in the Task reporting that it was cancelled.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <LangVersion>latest</LangVersion>
  </PropertyGroup>

</Project>
class Program
{
    static async Task Main(string[] args)
    {
        var task = Task.Run(() => throw new OperationCanceledException());
        try { await task; } catch { }
        Console.WriteLine(task.IsCanceled); // Outputs "True"
    }
}

Environment

Microsoft Visual Studio Professional 2017 Version 15.5.4 (VisualStudio.15.Release/15.5.4+27130.2024)
Microsoft .NET Framework Version 4.7.02556
dotNET Version 2.1.4

Question

Should a Task report that it's cancelled in this case? If it is, there's a documentation bug—and I can work on a documentation PR addressing it. If it shouldn't, it looks like there's a code bug somewhere.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.ThreadingquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions