TaskFactory::StartNew Method (Action, CancellationToken)

Creates and starts a Task.

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

public:
Task^ StartNew(
	Action^ action, 
	CancellationToken cancellationToken
)

Parameters

action
Type: System::Action

The action delegate to execute asynchronously.

cancellationToken
Type: System.Threading::CancellationToken

The CancellationToken that will be assigned to the new task.

Return Value

Type: System.Threading.Tasks::Task
The started Task.

ExceptionCondition
ObjectDisposedException

The provided CancellationToken has already been disposed.

ArgumentNullException

The exception that is thrown when the action argument is null.

Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Task::Run(Action, CancellationToken) method as a quick way to call StartNew(Action, CancellationToken) with default parameters. Note, however, that there is a difference in behavior between the two methods regarding child tasks: Task::Run(Action, CancellationToken) by default does not allow child tasks started with the TaskCreationOptions::AttachedToParent option to attach to the current Task instance, whereas StartNew(Action, CancellationToken) does. For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

The following example calls the StartNew(Action, CancellationToken) method to create a task that iterates the files in the C:\Windows\System32 directory. The lambda expression calls the Parallel::ForEach method to add information about each file to a List<T> object. Each detached nested task invoked by the Parallel::ForEach 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.

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

.NET Framework

Supported in: 4.6, 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2015 Microsoft