Try removing the ct and use ts.Token instead of ct.
C# My Task is not getting cancel or aborted

T.Zacks
3,936
Reputation points
My Task is not getting cancel or aborted. if i could abort then count down will be stopped but ts.Cancel(); does not cancel the task. please see the code and guide me what to change in code.
CancellationToken ct;
CancellationTokenSource ts = new CancellationTokenSource();
private void button3_Click(object sender, EventArgs e)
{
int counter = 1;
Task.Factory.StartNew(() =>
{
while (true)
{
// do some heavy work here
Thread.Sleep(100);
if (ct.IsCancellationRequested)
{
// another thread decided to cancel
if (this.labelControl1.InvokeRequired)
{
this.labelControl1.BeginInvoke((MethodInvoker)delegate () { this.labelControl1.Text = "Task Cancel"; });
}
break;
}
else
{
if (this.labelControl1.InvokeRequired)
{
this.labelControl1.BeginInvoke((MethodInvoker)delegate () { this.labelControl1.Text = "counter "+ counter; });
counter++;
}
}
}
}, ct);
}
private void button4_Click(object sender, EventArgs e)
{
ts.Cancel();
}
Thanks