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.