Task.FromException メソッド

定義

オーバーロード

FromException(Exception)

指定した例外で完了した Task を作成します。

FromException<TResult>(Exception)

指定した例外で完了した Task<TResult> を作成します。

FromException(Exception)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

指定した例外で完了した Task を作成します。

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
Public Shared Function FromException (exception As Exception) As Task

パラメーター

exception
Exception

タスクを完了させる例外。

戻り値

エラーが発生したタスク。

注釈

このメソッドは、 プロパティが Task で、そのプロパティに ExceptionStatusFaulted が含まれる オブジェクトを作成します。exception メソッドは、タスクが実行する作業によって、長いコード パスを実行する前に例外がスローされることがわかっている場合に一般的に使用されます。 例については、 オーバーロードに関するページを FromException<TResult>(Exception) 参照してください。

適用対象

FromException<TResult>(Exception)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

指定した例外で完了した Task<TResult> を作成します。

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>
Public Shared Function FromException(Of TResult) (exception As Exception) As Task(Of TResult)

型パラメーター

TResult

タスクによって返される結果の型。

パラメーター

exception
Exception

タスクを完了させる例外。

戻り値

エラーが発生したタスク。

次の例は、コマンド ライン 引数として名前が渡される各ディレクトリ内のファイル内のバイト数を計算するコマンド ライン ユーティリティです。 この例では、オブジェクトをインスタンス化 FileInfo し、ディレクトリ内の各ファイルのプロパティの値を FileInfo.Length 取得する長いコード パスを実行するのではなく、 メソッドを呼び出 FromException<TResult>(Exception) して、特定のサブディレクトリが存在しない場合にエラーが発生したタスクを作成します。

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
open System
open System.IO
open System.Threading
open System.Threading.Tasks

let getFileLengthsAsync filePath =
    if Directory.Exists filePath |> not then
        DirectoryNotFoundException "Invalid directory name."
        |> Task.FromException<int64>

    else
        let files = Directory.GetFiles filePath

        if files.Length = 0 then
            Task.FromResult 0L
        else
            Task.Run(fun () ->
                let mutable total = 0L

                Parallel.ForEach(
                    files,
                    fun fileName ->
                        use fs =
                            new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 256, true)

                        Interlocked.Add(ref total, fs.Length) |> ignore
                )
                |> ignore

                total)

let args = Environment.GetCommandLineArgs()[1..]

if args.Length > 0 then
    let tasks = Array.map getFileLengthsAsync args

    try
        Seq.cast tasks |> Seq.toArray |> Task.WaitAll

    // Ignore exceptions here.
    with :? AggregateException ->
        ()

    for i = 0 to tasks.Length - 1 do
        if tasks[i].Status = TaskStatus.Faulted then
            printfn $"{args[i + 1]} does not exist"
        else
            printfn $"{tasks[i].Result:N0} bytes in files in '{args[i + 1]}'"
else
    printfn "Syntax error: Include one or more file paths."

// 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> で、そのプロパティに ExceptionStatusFaulted が含まれる オブジェクトを作成します。exception メソッドは、タスクが実行する作業によって、長いコード パスを実行する前に例外がスローされることがわかっている場合に一般的に使用されます。 具体的な例を次に示します。

適用対象