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