C# My Task is not getting cancel or aborted

T.Zacks 3,986 Reputation points
2022-10-28T14:21:47.37+00:00

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

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,293 questions
{count} votes

Accepted answer
  1. Viorel 112.5K Reputation points
    2022-10-28T14:52:45.867+00:00

    Try removing the ct and use ts.Token instead of ct.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful