Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix an IAsyncDisposable Object Whose DisposeAsync Never Runs Because It Was Disposed Synchronously by Mistake

- 11.10.26 - ErcanOPAK

🔧 The DisposeAsync That Was Called the Synchronous Way

A type can implement both IDisposable and IAsyncDisposable at once, which is common for anything that wraps a resource with async-friendly cleanup, like flushing a buffered stream over the network. The two interfaces look interchangeable from the call site because a using statement compiles against either one, but they are not interchangeable in what actually runs: a plain using block, or an explicit call to Dispose, invokes only the synchronous Dispose path, and if that type’s Dispose method is a thin fallback that skips the async flush entirely, the object’s real cleanup logic in DisposeAsync never executes at all, with no exception or warning to say so.

🔎 The Problem

public sealed class BufferedUploadSession : IDisposable, IAsyncDisposable
{
    public void Dispose()
    {
        // The synchronous fallback. It releases the handle, but it
        // does NOT flush the buffered bytes - that part only
        // happens in DisposeAsync below, by design, because
        // flushing requires an async network write.
        _handle?.Dispose();
    }

    public async ValueTask DisposeAsync()
    {
        await _networkStream.FlushAsync();
        _handle?.Dispose();
    }
}

public void UploadReport(byte[] data)
{
    // A plain 'using' block binds to IDisposable, not
    // IAsyncDisposable - this silently calls Dispose(), not
    // DisposeAsync(), even though the type implements both.
    using var session = new BufferedUploadSession();
    session.Write(data);
} // the buffered bytes are never flushed; the file is incomplete

✅ Fix: Use await using to Reach the Async Path

  • Switch the call site to await using instead of a plain using whenever the object implements IAsyncDisposable, so DisposeAsync is the method that actually runs – the compiler only picks the async path when the code explicitly asks for it with await using, never automatically just because the type offers both.
  • When a type implements both interfaces, make the synchronous Dispose perform the same cleanup as DisposeAsync wherever that’s actually possible – blocking on the async work inside Dispose if there’s truly no other option – rather than leaving Dispose as a silent partial fallback that skips the real cleanup entirely.
  • Add a debug-only check inside Dispose that asserts or logs loudly whenever it runs on a type that also implements IAsyncDisposable, so a using block that should have been await using fails fast in testing instead of shipping a quietly incomplete cleanup to production.

⚠️ Why This Is Easy to Miss

  • The compiler accepts a plain using block on a type that implements IAsyncDisposable without any warning at all, because IDisposable alone is sufficient to satisfy it – nothing short of actually reading both Dispose and DisposeAsync side by side reveals that only one of them does the real work.
  • The missing flush often doesn’t fail loudly – it produces a file or a message that’s merely short by whatever was still sitting in the buffer, which can look like a legitimate data issue somewhere upstream rather than a disposal problem in this exact method.

IDisposable and IAsyncDisposable on the same type are two different doors into cleanup – using only ever opens one of them, and nothing forces you to notice which.

— C# Best Practice

Related posts:

How to calculate difference (number of days) between two dates in C#

How to calculate difference (number of days) between two dates in C#

C#: Use Pattern Matching for Elegant Code

C#: Use Pattern Matching for Elegant Code

How to lock the ciritical code part in C#

How to lock the ciritical code part in C#

Views: 4

Post navigation

Windows 11: Fix Phone Link Notifications That Silently Stop Arriving Because Battery Optimization Paused It in the Background
SQL Server: Fix a Table Variable That Forces a Serial Query Plan Because It Carries No Column Statistics for the Optimizer to Use

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com