Task.Run<'TResult> Method (Func<'TResult>, CancellationToken)

.NET Framework (current version)

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Queues the specified work to run on the thread pool and returns a Task(TResult) object that represents that work. A cancellation token allows the work to be cancelled.

Namespace:   System.Threading.Tasks
Assembly:  mscorlib (in mscorlib.dll)

static member Run<'TResult> : 
        function:Func<'TResult> *
        cancellationToken:CancellationToken -> Task<'TResult>


Type: System.Func<'TResult>

The work to execute asynchronously

Type: System.Threading.CancellationToken

A cancellation token that should be used to cancel the work

Return Value

Type: System.Threading.Tasks.Task<'TResult>

A Task(TResult) that represents the work queued to execute in the thread pool.

Type Parameters


The result type of the task.

Exception Condition

The function parameter is null.


The task has been canceled.


The CancellationTokenSource associated with cancellationToken was disposed.

If cancellation is requested before the task begins execution, the task does not execute. Instead it is set to the Canceled state and throws a TaskCanceledException exception.

The Run<'TResult> method is a simpler alternative to the StartNew method. It creates a task with the following default values:

For information on handling exceptions thrown by task operations, see Exception Handling (Task Parallel Library).

The following example creates 20 tasks that will loop until a counter is incremented to a value of 2 million. When the first 10 tasks reach 2 million, the cancellation token is cancelled, and any tasks whose counters have not reached 2 million are cancelled. The example shows possible output.

No code example is currently available or this language may not be supported.

Instead of using the InnerExceptions property to examine exceptions, the example iterates all tasks to determine which have completed successfully and which have been cancelled. For those that have completed, it displays the value returned by the task.

Because cancellation is cooperative, each task can decide how to respond to cancellation. The following example is like the first, except that, once the token is cancelled, tasks return the number of iterations they've completed rather than throw an exception.

No code example is currently available or this language may not be supported.

The example still must handle the AggregateException exception, since any tasks that have not started when cancellation is requested still throw an exception.

Universal Windows Platform
Available since 8
.NET Framework
Available since 4.5
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1
Return to top