Hamza
Hamza

Reputation: 2413

C#: Task cancellation not working (CancellationTokenSource)

I have some long running code that I would like to run as a Task and cancel when needed using CancellationTokenSource but cancellation doesn't seem to work as my task keeps running when tokenSource.Cancel() is called (no exception thrown).

Probably missing something obvious?

Cut down example below:

bool init = false;

private void Button1_Click(object sender, EventArgs e)
{
    CancellationTokenSource tokenSource = new CancellationTokenSource();
    CancellationToken token = tokenSource.Token;
    Task task = new Task(() =>
    {
        while (true)
        {
            token.ThrowIfCancellationRequested();

            if (token.IsCancellationRequested)
            {
                Console.WriteLine("Operation is going to be cancelled");
                throw new Exception("Task cancelled");
            }
            else
            {
                // do some work
            }
        }
    }, token);

    if (init)
    {
        tokenSource.Cancel();
        button1.Text = "Start again";
        init = false;
    } else
    {
        try
        {
            task.Start();
        } catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        button1.Text = "Cancel";
        init = true;
    }
}

Upvotes: 0

Views: 1039

Answers (1)

Lukasz Szczygielek
Lukasz Szczygielek

Reputation: 3129

Main issue in your code is that you don't store a tokenSource. Second Button1_Click invocation cancels different token than you pass to task during first call.

Second issue is that you create over and over again new task, but your logic suggest that you want one task which should be created on first click and terminated during second click.

Upvotes: 3

Related Questions