CodexBloom - Programming Q&A Platform

C# - How to Properly Implement IDisposable in a Custom Class with Asynchronous Operations?

πŸ‘€ Views: 75 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-25
c# async-await disposable best-practices C#

I'm optimizing some code but I tried several approaches but none seem to work. I'm confused about I'm struggling with implementing the `IDisposable` pattern in my custom class that performs asynchronous operations. My class, `AsyncResourceHandler`, manages external resources that need to be cleaned up properly, but I also have an asynchronous method that may still be running when I call `Dispose()`. I want to ensure that resources are released without causing race conditions or accessing disposed objects. Here’s a simplified version of my class: ```csharp public class AsyncResourceHandler : IDisposable { private bool disposed = false; private CancellationTokenSource cancellationTokenSource; public AsyncResourceHandler() { cancellationTokenSource = new CancellationTokenSource(); } public async Task SomeAsyncOperation() { // Simulating asynchronous work await Task.Delay(5000, cancellationTokenSource.Token); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // Free managed resources cancellationTokenSource.Cancel(); cancellationTokenSource.Dispose(); } // Free unmanaged resources disposed = true; } } } ``` When I call `Dispose()`, if `SomeAsyncOperation()` is still running, it throws an `ObjectDisposedException`. I've tried checking the `disposed` flag before proceeding with operations, but I still encounter issues, especially when trying to access `cancellationTokenSource` in both `Dispose()` and `SomeAsyncOperation()`. What’s the best way to handle the disposal of resources in this case? Should I be awaiting the task in `Dispose()` or is there a better pattern to ensure that both disposal and asynchronous operations work harmoniously? Has anyone else encountered this? I'm on Ubuntu 22.04 using the latest version of C#. Any ideas how to fix this?