you are confusing Cancellation (controlled exit) with abort.
- abort kills a thread and thows thread exception. all variables, especially statics are left in an unknown state.
- cancellation is a message to a thread to gracefully exit.
for Cancellation to work, the thread must implement support for cancelation. say in your code:
private void Test()
{
if (this.labelControl1.InvokeRequired)
{
this.labelControl1.BeginInvoke((MethodInvoker)delegate () { this.labelControl1.Text = "Task Start"; });
}
for (var I=0; I < 10000; ++i)
{
if (ct.IsCancellationRequested)
{
ct.ThrowIfCancellationRequested();
return;
}
System.Threading.Thread.Sleep(1);
}
}
then in the
private void button4_Click(object sender, EventArgs e)
{
//Cancel the task
ts.Cancel();
if (this.labelControl1.InvokeRequired)
{
this.labelControl1.BeginInvoke((MethodInvoker)delegate () { this.labelControl1.Text = "Task Cancel"; });
}
}
you might want to add a watchdog timer to abort the task if it does not gracefully exit