Task(Of TResult) Constructor (Func(Of TResult))


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Initializes a new Task(Of TResult) with the specified function.

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

Public Sub New (
	function As Func(Of TResult)


Type: System.Func(Of TResult)

The delegate that represents the code to execute in the task. When the function has completed, the task's Result property will be set to return the result value of the function.

Exception Condition

The function argument is null.

Rather than calling this constructor, the most common way to instantiate a Task(Of TResult) object and launch a task is by calling the static Task.Run(Of TResult)(Func(Of TResult)) and TaskFactory(Of TResult).StartNew(Func(Of TResult)) methods. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

The following example counts the approximate number of words in text files that represent published books. Each task is responsible for opening a file, reading its entire contents asynchronously, and calculating the word count by using a regular expression. The Task.WaitAll(Task()) method is called to ensure that all tasks have completed before displaying the word count of each book to the console.

Object instantiation is separated from object execution in this example so that the example can ensure that each file exists. If they do not, it displays the name of the missing file. Otherwise, it calls the Task.Start method to launch each task.

Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim pattern As String = "\p{P}*\s+"
      Dim titles() As String = { "Sister Carrie",
                                 "The Financier" }
      Dim tasks(titles.Length - 1) As Task(Of Integer)

      For ctr As Integer = 0 To titles.Length - 1
         Dim s As String = titles(ctr)
         tasks(ctr) = New Task(Of Integer)( Function()
                                   ' Number of words.
                                   Dim nWords As Integer = 0
                                   ' Create filename from title.
                                   Dim fn As String = s + ".txt"

                                   Dim sr As New StreamReader(fn)
                                   Dim input As String = sr.ReadToEndAsync().Result
                                   nWords = Regex.Matches(input, pattern).Count
                                   Return nWords
                                End Function)

      ' Ensure files exist before launching tasks.
      Dim allExist As Boolean = True
      For Each title In titles
         Dim fn As String = title + ".txt"
         If Not File.Exists(fn) Then
            allExist = false
            Console.WriteLine("Cannot find '{0}'", fn)
            Exit For
         End If   
      ' Launch tasks 
      If allExist Then
         For Each t in tasks

         Console.WriteLine("Word Counts:")
         For ctr As Integer = 0 To titles.Length - 1
         Console.WriteLine("{0}: {1,10:N0} words", titles(ctr), tasks(ctr).Result)
      End If   
   End Sub
End Module
' The example displays the following output:
'       Sister Carrie:    159,374 words
'       The Financier:    196,362 words

The regular expression pattern \p{P}*\s+ matches zero, one, or more punctuation characters followed by one or more whitespace characters. It assumes that the total number of matches equals the approximate word count.

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