Task<TResult>.Result 속성

정의

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>값의 결과 값입니다.

예외

작업이 취소되었습니다. InnerExceptions 컬렉션에 TaskCanceledException 개체가 있습니다.

또는 작업을 실행하는 동안 예외가 발생한 경우 예외나 예외에 대한 정보를 포함하는 InnerExceptions 컬렉션입니다.

예제

다음 예제는 이름이 명령줄 인수로 전달되는 각 디렉터리의 파일에서 바이트 수를 계산하는 명령줄 유틸리티입니다. 디렉터리에 파일이 포함된 경우 디렉터리의 각 파일에 대한 개체를 인스턴스화 FileStream 하고 해당 FileStream.Length 속성의 값을 검색하는 람다 식을 실행합니다. 디렉터리에 파일이 없는 경우 단순히 메서드를 FromResult 호출하여 속성이 0인 Task<TResult>.Result 작업을 만듭니다. 작업이 완료되면 모든 디렉터리 파일의 총 바이트 수를 속성에서 Result 사용할 수 있습니다.

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 하는 것과 같습니다.

작업의 결과를 사용할 수 있게 되면 저장되고 속성에 대한 후속 호출 Result 시 즉시 반환됩니다. 작업을 수행하는 동안 예외가 발생하거나 작업이 취소된 경우 속성은 Result 값을 반환하지 않습니다. 대신 속성 값에 액세스하려고 시도하면 예외가 AggregateException throw됩니다.

적용 대상

추가 정보