Click here to Skip to main content
13,293,474 members (49,965 online)
Click here to Skip to main content
Add your own
alternative version


7 bookmarked
Posted 11 Mar 2014

Cancel a Loop in a Task with CancellationTokens

, 11 Mar 2014
Rate this:
Please Sign up or sign in to vote.
Cancel a loop in a task with CancellationTokens


In the event that you create an asynchronous Task with a loop, in which you run your code, say you’ve created an asynchronous task. The method you’re running inside your task contains a loop (infinite or not), and you want to break out of it, peacefully. You would need to create a CancellationTokenSource and pass the Task.Factory.StartNew method the cancellation Token, also passing the token to the main loop.

A CancellationTokenSource provides a way of signaling its Cancellation Token that it has been cancelled. A CancellationToken notifies the operation that it should be cancelled.

I am creating a new Task using the Factory property of the Task. I could have created it in a different way, check here for Task Constructors. I am also using the parameters TaskCreationOption.LongRunningTask and TaskScheduler.Default.



Specifies that a task will be a long-running, coarse-grained operation involving fewer, larger components than fine-grained systems. It provides a hint to the TaskScheduler that oversubscription may be warranted. Oversubscription lets you create more threads than the available number of hardware threads.


Gets the default TaskScheduler instance that is provided by the .NET Framework.

Here is a simple example on how to achieve this. You can run this code on LinqPad or create a new console project. Just remember to include the System.Threading.Tasks namespace.

void Main()
    CancellationTokenSource cts = new CancellationTokenSource();
    var token = cts.Token;
    Task t = Task.Factory.StartNew( 
        () => {
    catch( AggregateException ae )
        // catch inner exception 
    catch( Exception crap )
        // catch something else

void MainLoop( CancellationToken token )
    while( true )
        // do something here.
        // Poll on this property if you have to do 
        // other cleanup before throwing. 
        if (token.IsCancellationRequested)
            // Clean up here, then...

After creating the Task, it will start automatically. All you have to do is to wait for the result, in this case there won’t be any variable returned, but you have to do this so you can recover if you get an AggregatedException.

To cancel the Task, just call the method Cancel from the CancellationTokenSource. Inside your method, the IsCancellationRequested property from the token will be true, giving you time to do some cleanup before throwing the cancellation request.

That’s pretty much it.

Get more information about C# Tasks and the Task Parallelism Library.

I hope you enjoyed this little explanation. Tasks are way much more than this little code snippet, so if you’re interested, check back once in a while, I’ll put up more snippets.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Michael Adaixo
Software Developer SkyBelow
Portugal Portugal
I am a regular guy who likes to design and write software and games. I'm currently living in Covilhã, Portugal, where I'm finishing my MSc in Computer Science and Engineering.

In my spare time I develop and design video games for PC and mobile platforms using Unity3D. I also like to develop tools to help developers.

I also like to workout, play sports, go to the movies and hangout with my friends.

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171207.1 | Last Updated 12 Mar 2014
Article Copyright 2014 by Michael Adaixo
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid