9

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)); 
            Thread1.Start();
            Thread2 = new Thread(() => Method2(CTSSend.Token)); 
            Thread2.Start();
        }
        else
        {
            CTSSend.Cancel();
            CTSSend.Dispose();
            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)
        {
            CTSSend.Cancel();
            CTSSend.Dispose();
        }
        if (CTSReceive != null)
        {
            CTSReceive.Cancel();
            CTSReceive.Dispose();
        }

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?

EDIT:

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.

Zerowalker
  • 761
  • 2
  • 8
  • 27
  • 4
    It´s a "duplicate" yes, but the other doesn´t really get an Answer, everyone says different. Some says, it´s okay to let it be, other says, you Must dispose of it. And i wonder, how can you dispose of it without have a chance of an exception when you close if it´s already disposed. – Zerowalker Aug 26 '13 at 17:41

1 Answers1

6

They did some analysis here When to dispose CancellationTokenSource? and it seems that it's quite useless to try to correctly dispose it. Let the GC collect it (and if you look in nearly all the examples of MSDN it isn't disposed)

Community
  • 1
  • 1
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • 4
    `IDisposable` instances should be disposed, even if it's inconvenient to do so. – Samuel Neff Aug 26 '13 at 13:54
  • 1
    @SamuelNeff So in Winforms apps all the controls are disposed? :-) The keyword here is "should", not "must". – xanatos Aug 26 '13 at 13:56
  • @SamuelNeff I'll add that I did some research... For example, on something connected like `Task`: http://stackoverflow.com/a/5986082/613130 – xanatos Aug 26 '13 at 13:58
  • 8
    @SamuelNeff And from there, to the linked response of Stephen Toub on msdn: `In short, as is typically the case in .NET, dispose aggressively *if* it's easy and correct to do based on the structure of your code. If you start having to do strange gyrations in order to Dispose (or in the case of Tasks, use additional synchronization to ensure it's safe to dispose, since Dispose may only be used once a task has completed), it's likely better to rely on finalization to take care of things.` – xanatos Aug 26 '13 at 14:00
  • 1
    @xanatos. About Winforms, yes, that should be disposed explicitly, essentially because most of the graphics is not managed. However, I don't see a "strict" reason for the CTS. The Toub's answer says perfectly what to do. – Mario Vernari Aug 26 '13 at 14:08
  • @MarioVernari A correctly built disposable class calls Dispose on finalizer, so there isn't really any problem on resources like the ones in GDI, unless you create and destroy them in rapid succession – xanatos Aug 26 '13 at 14:17
  • I'd have a suspect on the CancelAfter method invoking, which starts a timer, and a timer running will hold the callback instance alive. Anyway, it seems safe as well. About Winforms, I trust you: I seldom use them. In WPF the disposal is almost useless. – Mario Vernari Aug 26 '13 at 14:23
  • The documentation in 2020 clearly says: `Important The CancellationTokenSource class implements the IDisposable interface. You should be sure to call the CancellationTokenSource.Dispose method when you have finished using the cancellation token source to free any unmanaged resources it holds.` - https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads?view=netframework-4.8 – Endrju Feb 17 '20 at 20:26