0

I created a new task. I'm uisng a while inside. I want to somehow to stop it.

 Task task;
    CancellationTokenSource cts;

    private  void button1_ClickAsync(object sender, EventArgs e)
    {
        cts = new CancellationTokenSource();
        task  = Task.Factory.StartNew(Run2, cts.Token);


    }
    void Run2()
    {
        int i = 0;
        while (true)
        {

            i++;
            Write(Convert.ToString(i));
           // textBox1.Text = Convert.ToString(i);
            Thread.Sleep(1000);
        }
    }
    public void Write(string value)
    {
        if (InvokeRequired)
        {
            this.Invoke(new Action<string>(Write), new object[] { value });
          //  return;
        }
        textBox1.Text = value;
    }

    private void button2_Click(object sender, EventArgs e)
    { 
            cts.Cancel();

    }
}

When i'm using cancel button my task doesn't stop. My TextBox is still increasing.

Dhi
  • 157
  • 3
  • 11
  • `StartNew(Action, CTS)` will only prevent it from starting if the CTS was canceled. Try to check the CTS every now and then yourself in the loop. Also try to use Task.Delay instead of Thread.Sleep – Caramiriel Oct 19 '18 at 11:05
  • 1
    The task won't be killed, you will need to explicitly check for the cancellation token being cancelled inside the loop in `Run2`. The only purpose the cancellation token has in your `StartNew` call is that the task will not be spun up if it has already been cancelled, but after it has started, you do nothing to stop it. – Lasse V. Karlsen Oct 19 '18 at 11:05
  • You should check iscancelatinonrequested like: https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads – gabba Oct 19 '18 at 11:06
  • If you want to report progress use `IProgress`, not `Invoke`. Don't use `Thread.Sleep` either, that just wastes a thread. Change your method's signature to `async Task` and use `await Task.Delay(1000)` instead of `Thread.Sleep()` – Panagiotis Kanavos Oct 19 '18 at 11:08
  • Check Stephen Toub's article: [Enabling Progress and Cancellation in Async APIs](https://blogs.msdn.microsoft.com/dotnet/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis/) – Panagiotis Kanavos Oct 19 '18 at 11:10
  • Can i use task and changing values in ui thread without to using invoke? – Dhi Oct 19 '18 at 11:40

0 Answers0