TaskFactory.StartNew Method (Action, CancellationToken)


Creates and starts a Task.

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

Public Function StartNew (
	action As Action,
	cancellationToken As CancellationToken
) As Task


Type: System.Action

The action delegate to execute asynchronously.

Type: System.Threading.CancellationToken

The CancellationToken that will be assigned to the new task.

Return Value

Type: System.Threading.Tasks.Task

The started Task.

Exception Condition

The provided CancellationToken has already been disposed.


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 : 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(Of TSource) method to add information about each file to a List(Of T) object. Each detached nested task invoked by the Parallel.ForEach(Of 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.

Imports System.Collections.Generic
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tokenSource As New CancellationTokenSource()
      Dim token As CancellationToken = tokenSource.Token
      Dim files As New List(Of Tuple(Of String, String, Long, Date))()

      Dim t As Task = Task.Factory.StartNew( Sub()
                                   Dim dir As String = "C:\Windows\System32\"
                                   Dim obj As New Object()
                                   If Directory.Exists(dir)Then
                                            If token.IsCancellationRequested Then
                                            End If  
                                            Dim fi As New FileInfo(f)
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc))          
                                            End SyncLock
                                         End Sub)
                                   End If
                                End Sub, token)
         Console.WriteLine("Retrieved information for {0} files.", files.Count)
      Catch e As AggregateException
         Console.WriteLine("Exception messages:")
         For Each ie As Exception In e.InnerExceptions
            Console.WriteLine("   {0}:{1}", ie.GetType().Name, ie.Message)
         Console.WriteLine("Task status: {0}", t.Status)       
      End Try
   End Sub
End Module
' The example displays the following output:
'       Exception messages:
'          TaskCanceledException: A task was canceled.
'       Task status: Canceled

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