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.