Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Property | Value |
---|---|
Rule ID | CA2025 |
Title | Do not pass 'IDisposable' instances into unawaited tasks |
Category | Reliability |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 10 | As warning |
Cause
An IDisposable
instance is passed into an unawaited task and potentially disposed before the task is finished using the instance.
Rule description
Unawaited tasks that use IDisposable
instances might use those instances long after they've been disposed. Ensure tasks using those instances are completed before the instances are disposed.
Examples
The following code snippets (and their Visual Basic equivalents) are violations of CA2025:
public Task DoSomethingAsync()
{
// Using statements and using blocks can both be violations.
using (var disposable = new DisposableThing())
{
return DoSomethingInternalAsync(disposable);
}
}
public async Task DoThingsAsync()
{
var disposable = new DisposableThing();
var task = DoSomethingInternalAsync(disposable);
// More code here.
dispose.Dispose();
// It's a violation if arguments are disposed before the task is awaited.
await task.ConfigureAwait(false);
}
When to suppress warnings
Suppress these warnings if you know tasks finish using IDisposable
instances before they're disposed.
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 CA2025
// The code that's violating the rule is on this line.
#pragma warning restore CA2025
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA2025.severity = none
For more information, see How to suppress code analysis warnings.