Task<TResult>.Result 属性

定义

获取此 Task<TResult> 的结果值。Gets the result value of this Task<TResult>.

public:
 property TResult Result { TResult get(); };
public TResult Result { get; }
member this.Result : 'Result
Public ReadOnly Property Result As TResult

属性值

TResult

Task<TResult>的结果值, 其类型与任务的类型参数相同。The result value of this Task<TResult>, which is of the same type as the task's type parameter.

异常

已取消任务。The task was canceled. InnerExceptions 集合包含 TaskCanceledException 对象。The InnerExceptions collection contains a TaskCanceledException object.

-or- 执行任务期间引发了一个异常。An exception was thrown during the execution of the task. InnerExceptions 集合包含一个或多个异常的相关信息。The InnerExceptions collection contains information about the exception or exceptions.

示例

下面的示例是一个命令行实用工具, 该实用工具计算每个目录中的文件中其名称作为命令行参数传递的字节数。The following example is a command-line utility that calculates the number of bytes in the files in each directory whose name is passed as a command-line argument. 如果目录包含文件, 它将执行一个 lambda 表达式, 该表达式FileStream为目录中的每个文件实例化对象, 并检索FileStream.Length其属性的值。If the directory contains files, it executes a lambda expression that instantiates a FileStream object for each file in the directory and retrieves the value of its FileStream.Length property. 如果目录不包含任何文件, 它只需调用FromResult方法来创建其Task<TResult>.Result属性为零 (0) 的任务。If a directory contains no files, it simply calls the FromResult method to create a task whose Task<TResult>.Result property is zero (0). 任务完成后, 可从Result属性获取所有目录文件中的总字节数。When the tasks finish, the total number of bytes in all a directory's files is available from the Result property.

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

注解

访问属性的 get 访问器会阻止调用线程, 直到异步操作完成;它等效于调用Wait方法。Accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method.

操作结果可用后, 它将被存储并在对属性的Result后续调用后立即返回。Once the result of an operation is available, it is stored and is returned immediately on subsequent calls to the Result property. 请注意, 如果在任务的操作过程中发生异常, 或者如果任务已取消, 则Result属性不会返回值。Note that, if an exception occurred during the operation of the task, or if the task has been cancelled, the Result property does not return a value. 相反, 尝试访问属性值会引发AggregateException异常。Instead, attempting to access the property value throws an AggregateException exception.

适用于

另请参阅