本文整理匯總了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() {/*...*/ }
}