Export (0) Print
Expand All

Task.Run<TResult> Method (Func<TResult>)

.NET Framework 4.5

Queues the specified work to run on the thread pool and returns a Task<TResult> object that represents that work.

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

public static Task<TResult> Run<TResult>(
	Func<TResult> function
)

Type Parameters

TResult

The return type of the task.

Parameters

function
Type: System.Func<TResult>

The work to execute asynchronously.

Return Value

Type: System.Threading.Tasks.Task<TResult>
A task object that represents the work queued to execute in the thread pool.

ExceptionCondition
ArgumentNullException

The function parameter is null.

The Run method is a simpler alternative to the TaskFactory.StartNew(Action) method. It creates a task with the following default values:

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 WaitAll(Task[]) method is called to ensure that all tasks have completed before displaying the word count of each book to the console.

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] = Task.Run( () => {
                                   // Number of words. 
                                   int nWords = 0;
                                   // Create filename from title. 
                                   string fn = s + ".txt";
                                   if (File.Exists(fn)) {
                                      StreamReader sr = new StreamReader(fn);
                                      string input = sr.ReadToEndAsync().Result;
                                      nWords = Regex.Matches(input, pattern).Count;
                                   }
                                   return nWords;
                                } );
      }
      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 \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.

.NET Framework

Supported in: 4.6, 4.5

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Show:
© 2015 Microsoft