Task.FromResult<TResult>(TResult) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
创建指定结果的、成功完成的 Task<TResult>。
public:
generic <typename TResult>
static System::Threading::Tasks::Task<TResult> ^ FromResult(TResult result);
public static System.Threading.Tasks.Task<TResult> FromResult<TResult> (TResult result);
static member FromResult : 'Result -> System.Threading.Tasks.Task<'Result>
Public Shared Function FromResult(Of TResult) (result As TResult) As Task(Of TResult)
类型参数
- TResult
任务返回的结果的类型。
参数
- result
- TResult
存储入已完成任务的结果。
返回
已成功完成的任务。
示例
以下示例是一个命令行实用工具,用于计算每个目录中的字节数,其名称作为命令行参数传递。 如果某个目录没有文件,则示例只需调用该方法创建属性为零 (0) 的任务,而不是执行一个较长的代码路径来实例化 FileStream 对象并检索其 FileStream.Length 属性的值(如果目录没有文件),则此示例只需调用 FromResult 该方法即可创建 Task<TResult>.Result 属性为零 (0 的任务。
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
// the example displays output like the following:
// 0 bytes in files in 'subdir'
// 2,059 bytes in files in '.'
// newsubdir does not exist
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim args() As String = Environment.GetCommandLineArgs()
If args.Length > 1 Then
Dim tasks As New List(Of Task(Of Long))
For ctr = 1 To args.Length - 1
tasks.Add(GetFileLengthsAsync(args(ctr)))
Next
Try
Task.WaitAll(tasks.ToArray())
' Ignore exceptions here.
Catch e As AggregateException
End Try
For ctr As Integer = 0 To tasks.Count - 1
If tasks(ctr).Status = TaskStatus.Faulted Then
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))
End If
Next
Else
Console.WriteLine("Syntax error: Include one or more file paths.")
End If
End Sub
Private Function GetFileLengthsAsync(filePath As String) As Task(Of Long)
If Not Directory.Exists(filePath) Then
Return Task.FromException(Of Long)(
New DirectoryNotFoundException("Invalid directory name."))
Else
Dim files As String() = Directory.GetFiles(filePath)
If files.Length = 0 Then
Return Task.FromResult(0L)
Else
Return Task.Run( Function()
Dim total As Long = 0
Dim lockObj As New Object
Parallel.ForEach(files, Sub(fileName)
Dim fs As New FileStream(fileName, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite,
256, True)
Dim length As Long = fs.Length
Interlocked.Add(total, length)
fs.Close()
End Sub)
Return total
End Function )
End If
End If
End Function
End Module
' When launched with the following command line arguments:
' subdir . newsubdir
' the example displays output like the following:
' 0 bytes in files in 'subdir'
' 2,059 bytes in files in '.'
' newsubdir does not exist
注解
此方法创建一个 Task<TResult> 对象,其 Task<TResult>.Result 属性为 result
,其 Status 属性为 RanToCompletion. 当任务的返回值立即已知且不执行较长的代码路径时,通常会使用此方法。 说明如示例所示。
若要创建Task
不返回值的对象,请从CompletedTask属性中检索Task
对象。
从 .NET 6 开始,对于某些 T
类型和某些结果值,此方法可能会返回缓存的单一实例对象,而不是分配新对象。