TaskFactory.StartNew(Of TResult) Method (Func(Of TResult), CancellationToken)

 

Creates and starts a Task(Of TResult).

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

Public Function StartNew(Of TResult) (
	function As Func(Of TResult),
	cancellationToken As CancellationToken
) As Task(Of TResult)

Parameters

function
Type: System.Func(Of TResult)

A function delegate that returns the future result to be available through the Task(Of TResult).

cancellationToken
Type: System.Threading.CancellationToken

The CancellationToken that will be assigned to the new Task

Return Value

Type: System.Threading.Tasks.Task(Of TResult)

The started Task(Of TResult).

Type Parameters

TResult

The type of the result available through the Task(Of TResult).

Exception Condition
ObjectDisposedException

The provided CancellationToken has already been disposed.

ArgumentNullException

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

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

The following example uses two tasks to compute the Fibonacci sequence ending in F100 = F100-1 + F100-2 with seed values F1= 1, F2 = 1 and F1 = 0, F2= 1. Approximately half of the time, a cancellation token is set as the operations execute. The output from the example shows the result if the two tasks complete successfully and if the token is cancelled.

Imports System.Collections.Generic
Imports System.Numerics
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim tasks As New List(Of Task(Of BigInteger()))
      Dim source As New CancellationTokenSource
      Dim token As CancellationToken = source.Token
      For ctr As Integer = 0 To 1
         Dim start As Integer = ctr
         tasks.Add(Task.Run(Function()
                               Dim sequence(99) As BigInteger
                               sequence(0) = start
                               sequence(1) = 1
                               For index As Integer = 2 To sequence.GetUpperBound(0)
                                  token.ThrowIfCancellationRequested()
                                  sequence(index) = sequence(index - 1) + sequence(index - 2)
                               Next
                               Return sequence
                            End Function, token))
      Next
      If rnd.Next(0, 2) = 1 Then source.Cancel
      Try
         Task.WaitAll(tasks.ToArray())
         For Each t In tasks
            Console.WriteLine("{0}, {1}...{2:N0}", t.Result(0), t.Result(1),
                              t.Result(99))
         Next
      Catch e As AggregateException
         For Each ex In e.InnerExceptions
            Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message)
         Next
      End Try
   End Sub
End Module
' The example displays either the following output:
'    0, 1...218,922,995,834,555,169,026
'    1, 1...354,224,848,179,261,915,075
' or the following output:
'    TaskCanceledException: A task was canceled.
'    TaskCanceledException: A task was canceled.

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