0

I have started a task on Start Task button click and want to cancel that task > using Cancel Task button. But I am not able to find & cancel running task.

public ActionResult StartTask()
{
        var tokenSource = new CancellationTokenSource();
        CancellationToken ct = tokenSource.Token;

        Task.Factory.StartNew(() =>
        {
          // do some work...
        }, tokenSource.Token);

        return view();
}

public ActionResult CancelTask()
{
   //Here i want to cancel above task.
   return view();
}

Thanks in advance...

xpy
  • 5,481
  • 3
  • 29
  • 48

1 Answers1

0

Please try passing the CancellationToken as the second parameter to Task.Factory.StartNew

CancellationToken ct = tokenSource.Token;

    Task.Factory.StartNew(() =>
    {
            // do some work...

            if (ct.IsCancellationRequested)
            {
                // another thread decided to cancel
                Console.WriteLine("task canceled");
                break;
            }
    }, ct);

and issue tokenSource.Cancel() to cancel

Note: A similar thread can be found here How do I abort/cancel TPL Tasks?

Community
  • 1
  • 1
Guru Pasupathy
  • 440
  • 1
  • 4
  • 13