I have a UI button called Load. It spawns a thread, which in turn spawns a task. There is a wait on the task, and if it expires the task gets cancelled. The Load button is not disabled, and the user can click on it multiple times. Each time it's clicked the previous task should be cancelled.
I'm getting confused on how I should use the CancellationTokenSource and CancellationToken here. Below is the code. Can you please suggest how to use it and whether the below usage has any issues? No Async please as we are not there yet.
CancellationTokenSource _source = new CancellationTokenSource();
public void OnLoad()
{
//Does this cancel the previously spawned task?
_source.Cancel();
_source.Dispose();
_source = new CancellationTokenSource();
var activeToken = _source.Token;
//Do I need to do the above all the time or is there an efficient way?
Task.Factory.StartNew(() =>
{
var child = Task.Factory.StartNew(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(20));
activeToken.ThrowIfCancellationRequested();
}, activeToken);
if (!child.Wait(TimeSpan.FromSeconds(5)))
{
_source.Cancel();
}
});
}
Note I need to cancel any previously spawned tasks, and every spawned task should have a timeout.