Task.FromException Task.FromException Task.FromException Method

정의

오버로드

FromException(Exception) FromException(Exception) FromException(Exception)

지정된 예외를 사용하여 완료된 Task를 만듭니다.Creates a Task that has completed with a specified exception.

FromException<TResult>(Exception) FromException<TResult>(Exception) FromException<TResult>(Exception)

지정된 예외를 사용하여 완료된 Task<TResult>을 만듭니다.Creates a Task<TResult> that's completed with a specified exception.

FromException(Exception) FromException(Exception) FromException(Exception)

지정된 예외를 사용하여 완료된 Task를 만듭니다.Creates a Task that has completed with a specified exception.

public:
 static System::Threading::Tasks::Task ^ FromException(Exception ^ exception);
public static System.Threading.Tasks.Task FromException (Exception exception);
static member FromException : Exception -> System.Threading.Tasks.Task

매개 변수

exception
Exception Exception Exception

작업을 완료하는 데 사용할 예외입니다.The exception with which to complete the task.

반환

오류가 발생한 작업입니다.The faulted task.

설명

이 메서드를 만듭니다는 Task 개체 Status 속성은 FaultedException 속성에 들어 exception합니다.This method creates a Task object whose Status property is Faulted and whose Exception property contains exception. 메서드는 작업을 수행 하는 작업에서 예외가 발생 긴 코드 경로 실행 하기 전에 즉시 알고 있는 경우에 주로 사용 됩니다.The method is commonly used when you immediately know that the work that a task performs will throw an exception before executing a longer code path. 예를 들어 참조는 FromException<TResult>(Exception) 오버 로드 합니다.For an example, see the FromException<TResult>(Exception) overload.

FromException<TResult>(Exception) FromException<TResult>(Exception) FromException<TResult>(Exception)

지정된 예외를 사용하여 완료된 Task<TResult>을 만듭니다.Creates a Task<TResult> that's completed with a specified exception.

public:
generic <typename TResult>
 static System::Threading::Tasks::Task<TResult> ^ FromException(Exception ^ exception);
public static System.Threading.Tasks.Task<TResult> FromException<TResult> (Exception exception);
static member FromException : Exception -> System.Threading.Tasks.Task<'Result>

형식 매개 변수

TResult

작업에서 반환되는 결과의 형식입니다.The type of the result returned by the task.

매개 변수

exception
Exception Exception Exception

작업을 완료하는 데 사용할 예외입니다.The exception with which to complete the task.

반환

오류가 발생한 작업입니다.The faulted task.

예제

다음 예제는 이름이 명령줄 인수로 전달 되는 각 디렉터리에 있는 파일의 바이트 수를 계산 하는 명령줄 유틸리티입니다.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. 인스턴스화하는 긴 코드 경로 실행 하는 대신를 FileInfo 개체의 값을 검색 하 고 해당 FileInfo.Length 예제 디렉터리에 각 파일에 대 한 속성을 호출 합니다 FromException<TResult>(Exception) 특정 오류가 발생 한 작업을 만드는 방법 하위 디렉터리는 존재 하지 않습니다.Rather than executing a longer code path that instantiates a FileInfo object and retrieves the value of its FileInfo.Length property for each file in the directory, the example simply calls the FromException<TResult>(Exception) method to create a faulted task if a particular subdirectory does not exist.

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> 개체 Status 속성은 FaultedException 속성에 들어 exception합니다.This method creates a Task<TResult> object whose Status property is Faulted and whose Exception property contains exception. 메서드는 작업을 수행 하는 작업에서 예외가 발생 긴 코드 경로 실행 하기 전에 즉시 알고 있는 경우에 주로 사용 됩니다.The method is commonly used when you immediately know that the work that a task performs will throw an exception before executing a longer code path. 예제에서는 그림을 제공합니다.The example provides an illustration.

적용 대상