本文整理匯總了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;
}
}