Task.Run Method (Action, CancellationToken)
Queues the specified work to run on the thread pool and returns a Task object that represents that work. A cancellation token allows the work to be cancelled.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- action
-
Type:
System.Action
The work to execute asynchronously
- cancellationToken
-
Type:
System.Threading.CancellationToken
A cancellation token that can be used to cancel the work
Return Value
Type: System.Threading.Tasks.TaskA task that represents the work queued to execute in the thread pool.
| Exception | Condition |
|---|---|
| ArgumentNullException | The action parameter was 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(Action, CancellationToken) method is a simpler alternative to the TaskFactory.StartNew(Action, CancellationToken) 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 calls the Run(Action, CancellationToken) method to create a task that iterates the files in the C:\Windows\System32 directory. The lambda expression calls the Parallel.ForEach<'TSource> method to add information about each file to a List<'T> object. Each detached nested task invoked by the Parallel.ForEach<'TSource> loop checks the state of the cancellation token and, if cancellation is requested, calls the CancellationToken.ThrowIfCancellationRequested method. The CancellationToken.ThrowIfCancellationRequested method throws an OperationCanceledException exception that is handled in a catch block when the calling thread calls the Task.Wait method.
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