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.