Task::Run<TResult> Method (Func<TResult>^, CancellationToken)
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.
Assembly: mscorlib (in mscorlib.dll)
public: generic<typename TResult> static Task<TResult>^ Run( Func<TResult>^ function, CancellationToken cancellationToken )
Parameters
- function
-
Type:
System::Func<TResult>^
The work to execute asynchronously
- cancellationToken
-
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
- TResult
The result type of the task.
| Exception | Condition |
|---|---|
| ArgumentNullException | The function parameter is null. |
| TaskCanceledException | The task has been canceled. |
| ObjectDisposedException | 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:
Its CreationOptions property value is TaskCreationOptions::DenyChildAttach.
It uses the default task scheduler.
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.
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.
The example still must handle the AggregateException exception, since any tasks that have not started when cancellation is requested still throw an exception.
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
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.