Canceling a running Task:
A long running Task can be cancelled in a multithreaded environment. The .NET Framework offers a special class that can help you cancel a running task.
CancellationToken
- CancellationTokenSource tokenSource= new CancellationTokenSource();
- CancellationToken token = tokenSource.Token;
- Task t1 = Task.Factory.StartNew(() =>
- {
- while (!token.IsCancellationRequested)
- {
- Console.Write("* ");
- Thread.Sleep(1000);
- }
- },
- token);
- Console.WriteLine("Press any key to stop the task\n");
- Console.ReadKey();
- tokenSource.Cancel();
- Console.WriteLine("\n\nPress any key to stop the task");
- Console.ReadKey();
The CancellationToken is used in asynchronous task. The CancellationTokenSource token is used to signal that the Task should cancel itself.
In the above case, the operation will just end when cancellation is requested via Cancel() method. As the calling thread requests the cancellation on callee (i.e. Task running in another thread), outside users of the tasks won’t see anything different because the tasks will just have a RanToComplete state. The RanToComplete is the status of the task under consideration. If you want to signal to outside users that your task has been cancelled. You can do this by throwing an OperationCancelledException.
- CancellationTokenSource tokenSource = new CancellationTokenSource();
- CancellationToken token = tokenSource.Token;
- Task t1 = Task.Factory.StartNew(() =>
- {
- while (!token.IsCancellationRequested)
- {
- Console.Write("* ");
- Thread.Sleep(100); //Throw if cancelled
- }
- if (token.IsCancellationRequested)
- {
- token.ThrowIfCancellationRequested();
- }
- },
- token);
- try
- {
- Console.WriteLine("Press any key to stop the task\n");
- Console.ReadKey();
- tokenSource.Cancel();
- t1.Wait();
- }
- catch (AggregateException ex)
- {
- Console.WriteLine(“Exception Occured {0}”, ex.InnerExceptions[0].Message);
- }
- Console.WriteLine("\n\nPress any key to stop the task");
- Console.ReadKey();
- }
- CancellationTokenSource tokenSource = new CancellationTokenSource();
- CancellationToken token = tokenSource.Token;
- Task t1 = Task.Factory.StartNew(() =>
- {
- while (!token.IsCancellationRequested)
- {
- Console.Write("* ");
- Thread.Sleep(1000); //Throw if cancelled
- }
- },
- token).ContinueWith((t) =>
- {
- t.Exception.Handle((e)=> true);
- Console.WriteLine("The Task is interrupted");
- },
- TaskContinuationOptions.OnlyOnCanceled);
- Console.WriteLine("Press key any key to cancel\n");
- Console.ReadKey();
- tokenSource.Cancel();
- Console.WriteLine("\n\nEnd Application");
- Console.ReadKey();

Sanjay ShekhawatPosted Jun 25, 2019, 6:35 AM
Thanks, working Properly :)
Ammar ShaukatPosted Dec 20, 2017, 8:00 AM
Token.Cancel() is not enough to stop an ongoing task ?
SubashPosted Aug 1, 2016, 5:11 AM
Nice
Harshad PansuriyaPosted Nov 13, 2015, 10:59 PM
Nice one
Santhakumar MunuswamyPosted Nov 13, 2015, 10:12 AM
Good one
Former memberPosted Nov 13, 2015, 7:41 AM
:)
Shakti SaxenaPosted Nov 13, 2015, 7:39 AM
thanks for the feedback. I will think over it and incorporate the changes wherever required and will try to answer all your questions. :)
Former memberPosted Nov 13, 2015, 7:17 AM
Its very good article. But, some questions clicked in my mind after reading your mentioned line "In this case, the operation will just end when cancellation is requested" in this article. This line is confusing and not correct. So, Could you please update your article with the explanation of below question for the better quality of content?1) Does calling thread forcibly ends the Task?2) What happens if Taks is already running and cancellation is requested? 3) What happens if cancellation is requested before the Task runs?
Sibeesh VenuPosted Nov 13, 2015, 3:53 AM
Nice
Banketeshvar NarayanPosted Nov 13, 2015, 3:26 AM
Nice
Raja TPosted Nov 13, 2015, 12:28 AM
Nice ,Thanks for sharing..