本文整理匯總了C#中System.Threading.Tasks.Task<TResult>.Task構造函數的典型用法代碼示例。如果您正苦於以下問題:C# Task<TResult>構造函數的具體用法?C# Task<TResult>怎麽用?C# Task<TResult>使用的例子?那麽, 這裏精選的構造函數代碼示例或許可以為您提供幫助。您也可以進一步了解該構造函數所在類System.Threading.Tasks.Task<TResult>
的用法示例。
在下文中一共展示了Task<TResult>構造函數的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Main
//引入命名空間
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public class Example
{
public static async Task 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();
await Task.WhenAll(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);
}
}
}
輸出:
Sister Carrie: 159,374 words The Financier: 196,362 words