本文整理汇总了C#中System.Threading.Tasks.TaskFactory<TResult>类的典型用法代码示例。如果您正苦于以下问题:C# TaskFactory<TResult>类的具体用法?C# TaskFactory<TResult>怎么用?C# TaskFactory<TResult>使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
TaskFactory<TResult>类属于System.Threading.Tasks命名空间,在下文中一共展示了TaskFactory<TResult>类的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using System.IO;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
Task<string[]>[] tasks = new Task<string[]>[2];
String docsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
tasks[0] = Task<string[]>.Factory.StartNew( () => Directory.GetFiles(docsDirectory));
tasks[1] = Task<string[]>.Factory.StartNew( () => Directory.GetDirectories(docsDirectory));
Task.Factory.ContinueWhenAll(tasks, completedTasks => {
Console.WriteLine("{0} contains: ", docsDirectory);
Console.WriteLine(" {0} subdirectories", tasks[1].Result.Length);
Console.WriteLine(" {0} files", tasks[0].Result.Length);
} );
}
}
输出:
C:\Users\\Documents contains: 24 subdirectories 16 files
示例2: CancellationTokenSource
//引入命名空间
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
static CancellationTokenSource cts = new CancellationTokenSource();
static TaskFactory<int> factory = new TaskFactory<int>(
cts.Token,
TaskCreationOptions.PreferFairness,
TaskContinuationOptions.ExecuteSynchronously,
new CustomScheduler());
static void Main()
{
var t2 = factory.StartNew(() => DoWork());
cts.Dispose();
}
static int DoWork()
{
/*...*/
return DateTime.Now.Hour <= 12 ? 1 : 2;
}
}