I have a class which spawns various tasks which can run indefinitely. When this object is disposed, I want to stop those tasks from running.
Is this the correct approach:
public class MyClass : IDisposable
{
// Stuff
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
queueCancellationTokenSource.Cancel();
feedCancellationTokenSource.Cancel();
}
}
}
You're on the right track. However, I would suggest waiting for the task to terminate before returning from the
Dispose
method, in order to avoid race conditions where the task continues to operate after the object has been disposed. Also dispose theCancellationTokenSource
.