CA2247: Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum

Property Value
Rule ID CA2247
Title Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum
Category Usage
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 As warning

Cause

Constructing a System.Threading.Tasks.TaskCompletionSource with a System.Threading.Tasks.TaskContinuationOptions enum value rather than a System.Threading.Tasks.TaskCreationOptions enum value. Using System.Object.ReferenceEquals method to test one or more value types for equality.

Rule description

The TaskCompletionSource type has a constructor that accepts a System.Threading.Tasks.TaskCreationOptions enum value, and another constructor that accepts a Object. Accidentally passing a System.Threading.Tasks.TaskContinuationOptions enum value instead of a System.Threading.Tasks.TaskCreationOptions enum value will result in calling the Object-based constructor: it will compile and run, but it will not have the intended behavior.

How to fix violations

To fix the violation, replace the System.Threading.Tasks.TaskContinuationOptions enum value with the corresponding System.Threading.Tasks.TaskCreationOptions enum value.

    // Violation
    var tcs = new TaskCompletionSource<int>(TaskContinuationOptions.RunContinuationsAsynchronously);

    // Fixed
    var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);

When to suppress warnings

A violation of this rule almost always highlights a bug in the calling code, such that the code will not behave as the developer intended, with the TaskCompletionSource effectively ignoring the specified option. The only time it is safe to suppress the warning is if the developer actually intended to pass a boxed System.Threading.Tasks.TaskContinuationOptions as the object state argument to the TaskCompletionSource

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA2247
// The code that's violating the rule is on this line.
#pragma warning restore CA2247

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA2247.severity = none

To disable this entire category of rules, set the severity for the category to none in the configuration file.

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Usage.severity = none

For more information, see How to suppress code analysis warnings..

See also