3

So this is just a question sparked from curiosity. Consider the following code:

public class SomeClass : IDisposable 
{

    private CancellationTokenSource _cts;
    private Stream _stream;

    public SomeClass(Stream stream)
    {
        _stream = stream;
        _cts = new CancellationTokenSource();
    }

    // ...........

    private async Task DoStuff()
    {
        while(true)
        {
            if (_cts.IsCancellationRequested) return;

            // do some repetitive stuff here... 
        }
    }

    // ...........

    public async void Dispose()
    {
        _cts.Cancel();

        await Task.Delay(2000);

        // release stream or other resources...
    }
}

So this could be really bad practice or a complete no no... I am asking for the sake of knowledge. I just want to know what is happening to this dispose method. Does it run asynchronously? Is it going to do what I'm expecting it to do?

The idea is to cancel the cancellation token to stop a long running asynchronous task but allow a moment for it to potentially finish the iteration it is in before disposing the stream and causing object disposed or read/write errors in the task.

ArcX
  • 687
  • 8
  • 20
  • 6
    If you are targeting .NET Core, you could have `SomeClass` implement the interface [`IAsyncDisposable`](https://learn.microsoft.com/en-us/dotnet/api/system.iasyncdisposable), and inside the [`DisposeAsync`](https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.disposeasync) method you could `await` the `DisposeAsync` of the `_stream`. No artificial delays required. Related: [How to make Dispose await for all async methods?](https://stackoverflow.com/questions/56138952/how-to-make-dispose-await-for-all-async-methods) – Theodor Zoulias Nov 18 '19 at 08:46
  • 1
    @TheodorZoulias Wow, I didn't even realise `IAsyncDisposable` was a thing... Thanks for the alternative! – ArcX Nov 18 '19 at 09:20
  • 2
    It was released with .NET Core 3.0. If your project isn't targetting .NET Core 3, you can install the [`Microsoft.Bcl.AsyncInterfaces`](https://www.nuget.org/packages/Microsoft.Bcl.AsyncInterfaces/) NuGet package. – Gabriel Luci Nov 18 '19 at 12:14

0 Answers0