I want to start the async process by clicking the Start button, and cancel it via the Cancel button when necessary.
As expected I have started the async task on Start, but the issue is with Await. How to stop the async tasks which are currently running?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
CancellationTokenSource cs = new CancellationTokenSource();
private void Start(object sender, EventArgs e)
{
operate();
}
private void CancelProcess(object sender, EventArgs e)
{
cs.Cancel();
}
public async Task operate()
{
await Task.Factory.StartNew(() => progres(cs.Token), cs.Token);
}
void progres(CancellationToken css)
{
string o1 = Thread.CurrentThread.ManagedThreadId.ToString();
for (int i=0; i<101; i++)
{
Thread.Sleep(100);
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke(
(Action)delegate
{
progressBar1.Value = i;
textBox1.Text = o1;
});
}
else
{
progressBar1.Value = i;
}
}
}
}