C# 10 - Inconsistent Behavior with IAsyncDisposable and CancellationToken in Asynchronous Streams
I'm migrating some code and I'm encountering inconsistent behavior when using `IAsyncDisposable` with asynchronous streams in C# 10. I have a method that processes a stream of data from an external source, and I want to ensure proper disposal of resources when the operation is canceled via a `CancellationToken`. Here’s the code snippet I’m working with: ```csharp public async IAsyncEnumerable<string> GetDataAsync(CancellationToken cancellationToken) { using (var resource = new SomeResource()) { while (await resource.ReadAsync(cancellationToken) is string data) { yield return data; } } } ``` The issue arises when I pass the `CancellationToken` to the `ReadAsync` method. If the token is canceled while waiting for data, I receive an `OperationCanceledException`, but it seems that the `using` block is not completing correctly, and the disposal of `SomeResource` does not occur as expected. Here’s how I’m calling `GetDataAsync`: ```csharp public async Task ProcessDataAsync(CancellationToken cancellationToken) { await foreach (var item in GetDataAsync(cancellationToken)) { // process item } } ``` I’ve tried wrapping the call to `ReadAsync` in a try-catch block to handle the exception, but I still notice that the resource isn’t disposed correctly when an exception occurs. I also attempted using `Task.Run` to encapsulate the stream reading, but it didn’t resolve the issue. Is there a better approach to manage disposal in this context, or is there something I'm missing in the way I'm handling the cancellation? Any insights or best practices would be greatly appreciated! This is part of a larger service I'm building. Thanks for your help in advance!