0

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;
            }
        }
    }
}
Jens Hoffmann
  • 6,699
  • 2
  • 25
  • 31
  • did u chk https://stackoverflow.com/questions/10134310/how-to-cancel-a-task-in-await – Daniel B Oct 23 '17 at 15:41
  • 2
    Task cancellation is mutual, you must check `css.IsCancellationRequested` inside your method and exit if it's true. – Equalsk Oct 23 '17 at 15:42

0 Answers0