Task<TResult> Constructor (Func<TResult>)

 

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

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

public Task(
	Func<TResult> function
)

Parameters

function
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
ArgumentNullException

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.

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      string pattern = @"\p{P}*\s+";
      string[] titles = { "Sister Carrie", "The Financier" };
      Task<int>[] tasks = new Task<int>[titles.Length];

      for (int ctr = 0; ctr < titles.Length; ctr++) {
         string s = titles[ctr];
         tasks[ctr] = new Task<int>( () => {
                                   // Number of words.
                                   int nWords = 0;
                                   // Create filename from title.
                                   string fn = s + ".txt";

                                   StreamReader sr = new StreamReader(fn);
                                   string input = sr.ReadToEndAsync().Result;
                                   sr.Close();
                                   nWords = Regex.Matches(input, pattern).Count;
                                   return nWords;
                                } );
      }
      // Ensure files exist before launching tasks.
      bool allExist = true;
      foreach (var title in titles) {
         string fn = title + ".txt";
         if (! File.Exists(fn)) {
            allExist = false;
            Console.WriteLine("Cannot find '{0}'", fn);
            break;
         }   
      }
      // Launch tasks 
      if (allExist) {
         foreach (var t in tasks)
            t.Start();

        Task.WaitAll(tasks);

        Console.WriteLine("Word Counts:\n");
        for (int ctr = 0; ctr < titles.Length; ctr++)
           Console.WriteLine("{0}: {1,10:N0} words", titles[ctr], tasks[ctr].Result);
      }   
   }
}
// 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
Silverlight
Available since 5.0
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1
Return to top
Show: