When to dispose CancellationTokenSource?

The class CancellationTokenSource is disposable. A quick look in Reflector proves usage of KernelEvent, a (very likely) unmanaged resource. Since CancellationTokenSource has no finalizer, if we do not dispose it, the GC won't do it.

On the other hand, if you look at the samples listed on the MSDN article Cancellation in Managed Threads, only one code snippet disposes of the token.

What is the proper way to dispose of it in code?

  1. You cannot wrap code starting your parallel task with using if you do not wait for it. And it makes sense to have cancellation only if you do not wait.
  2. Of course you can add ContinueWith on task with a Dispose call, but is that the way to go?
  3. What about cancelable PLINQ queries, which do not synchronize back, but just do something at the end? Let's say .ForAll(x => Console.Write(x))?
  4. Is it reusable? Can the same token be used for several calls and then dispose it together with the host component, let's say UI control?

Because it does not have something like a Reset method to clean-up IsCancelRequested and Token field I would suppose it's not reusable, thus every time you start a task (or a PLINQ query) you should create a new one. Is it true? If yes, my question is what is the correct and recommended strategy to deal with Dispose on those many CancellationTokenSource instances?

Score: 172
Tags: c#, c#-4.0, task-parallel-library, plinq, parallel-extensions
Views: 51574
Date posted: 8/5/2011

ASP MVC: When is IController Dispose() called?

I'm going through a big refactoring / speed tweaking of one of my larger MVC apps. It has been deployed to production for a few months now, and I was starting to get timeouts waiting for connections in the connection pool. I have tracked the issue down to the connections not getting disposed properly.

In light of that, I have since made this change to my base controller:

public class MyBaseController : Controller
    private ConfigurationManager configManager;  // Manages the data context.

    public MyBaseController()
         configManager = new ConfigurationManager();

    protected override void Dispose(bool disposing)
        if (disposing)
            if (this.configManager != null)
                this.configManager = null;


Now, I have two questions:

  1. Am I introducing a race condition? Since the configManager manages the DataContext that exposes IQueryable<> parameters to the views, I need to make sure that Dispose() will not be called on the controller before the view finishes rendering.
  2. Does the MVC framework call Dispose() on the Controller before or after the view is rendered? Or, does the MVC framework leave that up to the GarbageCollector?
Score: 83
Tags: asp.net-mvc, linq-to-sql, garbage-collection, idisposable
Views: 26857
Date posted: 9/4/2009

When should I dispose of a data context

I'm currently writing a data access layer for an application. The access layer makes extensive use of linq classes to return data. Currently in order to reflect data back to the database I've added a private data context member and a public save method. The code looks something like this:

private DataContext myDb;
public static MyClass GetMyClassById(int id)
    DataContext db = new DataContext();
    MyClass result = (from item in db.MyClasss
                      where item.id == id
                      select item).Single();
    result.myDb = db;
    return result;

public void Save()

That's a gross over simplification but it gives the general idea. Is there a better way to handle that sort of pattern? Should I be instantiating a new data context every time i want to visit the db?

Score: 57
Tags: c#, linq, linq-to-sql
Views: 24272
Date posted: 12/23/2008

CancellationTokenSource, When to dispose?

When am i supposed to Dispose of a CancellationTokenSource? If i for example make one and put it in Threads everytime i click a button:

    private void Button_Click(object sender, EventArgs e)
        if (clicked == false)

            clicked = true;
            CTSSend = new CancellationTokenSource();
            Thread1 = new Thread(() => Method1(CTSSend.Token)); 
            Thread2 = new Thread(() => Method2(CTSSend.Token)); 
            clicked = false;

Am i supposed to dispose of it like that? Cause if so, it will be a bit problematic as i need to put it in the Disposer which will dispose when the application closes, as there isn´t a guarantee that it won´t be disposed already if i am not carefully waiting for it, and that will cause an ObjectDisposedException.

I even tried with this to prevent the exception (as i would like to not use Try Catch, i would like to not even get the error in the first place in this case).

        if (CTSSend != null)
        if (CTSReceive != null)

But well, maybe i should Only dispose of it in the end, and don´t dispose of it after Cancel everytime? Though i don´t like how that would keep adding resources to a new object.

How do you people do with these cases?


A more concrete question that will solve it (in my case).

How can i bound a bool to the CancellationToken? So i can have something like CTS.IsDisposed;

Some objects have that, but CTS doesn´t, if it had, it would solve the problem i am having. I am currently using a bool separately, which isn´t something i prefer.

Score: 9
Tags: c#, .net, multithreading
Views: 8664
Date posted: 8/26/2013

When to Dispose?

I'm getting confused about all this talk about IDispose and "using" Statements. I wonder if someone can tell me if I need to use either a "using" Statement or some sort of implementation of IDispose in the following test example...

public class Main()
    MyFile myFile = new MyFile("c:\subdir\subdir2\testFile.txt");
    Console.Writeline("File Name: " + myFile.FileName() + "File Size: " + myFile.FileSize());

public class MyFile
    private FileInfo _fInfo;

    public MyFile(string fullFilePath)
        _fInfo = new FileInfo(fullFilePath);

    public string FileName()
        return _fInfo.Name;

    public long FileSize()
        return _fInfo.Length;

Score: 8
Tags: c#, .net, idisposable, using-statement
Views: 1267
Date posted: 3/19/2012


© 2021 Search Overflow
Contributions licensed under cc by-sa