Export (0) Print
Expand All

TaskFactory.StartNew<TResult> Method (Func<TResult>, CancellationToken)

Creates and starts a Task<TResult>.

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

public Task<TResult> StartNew<TResult>(
	Func<TResult> function,
	CancellationToken cancellationToken
)

Type Parameters

TResult

The type of the result available through the Task<TResult>.

Parameters

function
Type: System.Func<TResult>

A function delegate that returns the future result to be available through the Task<TResult>.

cancellationToken
Type: System.Threading.CancellationToken

The CancellationToken that will be assigned to the new Task

Return Value

Type: System.Threading.Tasks.Task<TResult>
The started Task<TResult>.

ExceptionCondition
ObjectDisposedException

The provided CancellationToken has already been disposed.

ArgumentNullException

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

Calling StartNew is functionally equivalent to creating a Task<TResult> 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<TResult>(Func<TResult>, CancellationToken) method as a quick way to call StartNew<TResult>(Func<TResult>, CancellationToken) with default parameters. Note, however, that there is a difference in behavior between the two methods regarding child tasks: Task.Run<TResult>(Func<TResult>, CancellationToken) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task<TResult> instance, whereas StartNew<TResult>(Func<TResult>, CancellationToken) does. For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

.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
Show:
© 2015 Microsoft