Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CancellationTokenSource, When to dispose? [duplicate]

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.

like image 879
Zerowalker Avatar asked Aug 26 '13 12:08

Zerowalker


1 Answers

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)

like image 94
xanatos Avatar answered Sep 20 '22 09:09

xanatos