Task<'TResult> Constructor (Func<'TResult>)


Initializes a new Task<'TResult> with the specified function.

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

new : 
        function:Func<'TResult> -> Task


Type: System.Func<'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<'TResult> object and launch a task is by calling the static Task.Run<'TResult>(Func<'TResult>) and TaskFactory<'TResult>.StartNew(Func<'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.

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

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