Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CA2025 Do not pass IDisposable instances into unawaited tasks #7549

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

steveberdy
Copy link
Contributor

Unawaited tasks that use IDisposable instances may use those instances long after they have been disposed. Ensure tasks using those instances are completed before the instances are disposed.

Example case where the analyzer fires:

public static Task Case1Async()
{
    using (var ms = new MemoryStream())
    {
        return DoAsync(ms);
    }
}

The analyzer can detect more advanced use cases and choose not to fire, such as when the task is referenced and awaited later before its disposable arguments are disposed:

public Task Case2Async()
{
    var stream = new MemoryStream();
    var reader = new StreamReader(stream);

    var t = AnotherTaskAsync(stream, reader);
    // Some code here...
    await t.ConfigureAwait(false);
    // Dispose reader and stream...
}

Fixes dotnet/runtime#78394

@steveberdy steveberdy requested a review from a team as a code owner January 25, 2025 23:25
Copy link

codecov bot commented Jan 25, 2025

Codecov Report

Attention: Patch coverage is 98.60051% with 11 lines in your changes missing coverage. Please review.

Project coverage is 96.51%. Comparing base (3746107) to head (0d076be).

Additional details and impacted files
@@           Coverage Diff            @@
##             main    #7549    +/-   ##
========================================
  Coverage   96.50%   96.51%            
========================================
  Files        1452     1454     +2     
  Lines      347575   348361   +786     
  Branches    11418    11443    +25     
========================================
+ Hits       335436   336207   +771     
- Misses       9244     9252     +8     
- Partials     2895     2902     +7     

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Analyzer] Unawaited / returned tasks created with a disposable in using block for that disposable
1 participant