本文整理匯總了C#中System.Threading.Tasks.Task.FromResult<TResult>方法的典型用法代碼示例。如果您正苦於以下問題:C# Task.FromResult<TResult>方法的具體用法?C# Task.FromResult<TResult>怎麽用?C# Task.FromResult<TResult>使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Threading.Tasks.Task
的用法示例。
在下文中一共展示了Task.FromResult<TResult>方法的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Main
//引入命名空間
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1) {
List<Task<long>> tasks = new List<Task<long>>();
for (int ctr = 1; ctr < args.Length; ctr++)
tasks.Add(GetFileLengthsAsync(args[ctr]));
try {
Task.WaitAll(tasks.ToArray());
}
// Ignore exceptions here.
catch (AggregateException) {}
for (int ctr = 0 ; ctr < tasks.Count; ctr++) {
if (tasks[ctr].Status == TaskStatus.Faulted)
Console.WriteLine("{0} does not exist", args[ctr + 1]);
else
Console.WriteLine("{0:N0} bytes in files in '{1}'",
tasks[ctr].Result, args[ctr + 1]);
}
}
else {
Console.WriteLine("Syntax error: Include one or more file paths.");
}
}
private static Task<long> GetFileLengthsAsync(string filePath)
{
if (! Directory.Exists(filePath)) {
return Task.FromException<long>(
new DirectoryNotFoundException("Invalid directory name."));
}
else {
string[] files = Directory.GetFiles(filePath);
if (files.Length == 0)
return Task.FromResult(0L);
else
return Task.Run( () => { long total = 0;
Parallel.ForEach(files, (fileName) => {
var fs = new FileStream(fileName, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite,
256, true);
long length = fs.Length;
Interlocked.Add(ref total, length);
fs.Close(); } );
return total;
} );
}
}
}
// When launched with the following command line arguments:
// subdir . newsubdir
輸出:
0 bytes in files in 'subdir' 2,059 bytes in files in '.' newsubdir does not exist