本文整理汇总了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