Cancel tasks in the Dispose method

I have a class that spawns various tasks that can be performed endlessly. When this object is located, I want to stop these tasks.

This is 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(); } } } 
+7
c # parallel-processing idisposable task-parallel-library
source share
1 answer

You are on the right track. However, I suggest waiting for the task to complete before returning from the Dispose method to avoid race conditions when the task continues to work after the object has been deleted. Also post a CancellationTokenSource .

 public class MyClass : IDisposable { private readonly CancellationTokenSource feedCancellationTokenSource = new CancellationTokenSource(); private readonly Task feedTask; public MyClass() { feedTask = Task.Factory.StartNew(() => { while (!feedCancellationTokenSource.IsCancellationRequested) { // do finite work } }); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { feedCancellationTokenSource.Cancel(); feedTask.Wait(); feedCancellationTokenSource.Dispose(); feedTask.Dispose(); } } } 
+12
source share

All Articles