Rediger

Del via


CA2008: Do not create tasks without passing a TaskScheduler

Property Value
Rule ID CA2008
Title Do not create tasks without passing a TaskScheduler
Category Reliability
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 No

Cause

A task creation or continuation operation uses a method overload that does not specify a TaskScheduler parameter.

Rule description

The following .NET task creation and continuation methods have overloads that allow specifying or omitting a TaskScheduler instance:

Always specify an explicit TaskScheduler argument to avoid the default Current value, whose behavior is defined by the caller and may vary at run time. Current returns the scheduler associated with whatever Task is currently running on that thread. If there is no such task, it returns Default, which represents the thread pool. Using Current could lead to deadlocks or UI responsiveness issues in some situations, when it was intended to create the task on the thread pool, but instead it waits to get back onto the UI thread.

For further information and detailed examples, see New TaskCreationOptions and TaskContinuationOptions in .NET Framework 4.5.

How to fix violations

To fix violations, call the method overload that takes a TaskScheduler and explicitly pass in Default or Current to make the intent clear.

When to suppress warnings

This warning is intended primarily for libraries, where the code may be executed in arbitrary environments and where code shouldn't make assumptions about the environment or how the caller of the method may be invoking or waiting on it. It may be appropriate to suppress the warning for projects that represent application code rather than library code.

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 CA2008
// The code that's violating the rule is on this line.
#pragma warning restore CA2008

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

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

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

See also