Task.FromResult<TResult>(TResult) Methode

Definition

Erstellt ein Task<TResult>, die erfolgreich mit dem angegebenen Ergebnis abgeschlossen ist.Creates a Task<TResult> that's completed successfully with the specified result.

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)

Typparameter

TResult

Der Typ des von der Aufgabe zurückgegebenen Ergebnisses.The type of the result returned by the task.

Parameter

result
TResult

Das in der abgeschlossene Aufgabe zu speichernde Ergebnis.The result to store into the completed task.

Gibt zurück

Die erfolgreich abgeschlossene Aufgabe.The successfully completed task.

Beispiele

Das folgende Beispiel ist ein Befehlszeilen-Hilfsprogramm, das die Anzahl der Bytes in den Dateien in jedem Verzeichnis berechnet, dessen Name als Befehlszeilenargument übermittelt wird.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. Anstatt einen längeren Codepfad auszuführen, der ein FileStream-Objekt instanziiert und den Wert seiner FileStream.Length-Eigenschaft für jede Datei im Verzeichnis abruft, ruft das Beispiel einfach die FromResult-Methode auf, um eine Aufgabe zu erstellen, deren Task<TResult>.Result-Eigenschaft 0 (null) ist, wenn ein Verzeichnis hat keine Dateien.Rather than executing a longer code path that instantiates a FileStream object and retrieves the value of its FileStream.Length property for each file in the directory, the example simply calls the FromResult method to create a task whose Task<TResult>.Result property is zero (0) if a directory has no files.

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

Hinweise

Diese Methode erstellt ein Task<TResult>-Objekt, dessen Eigenschaft Task<TResult>.Result result und dessen Status-Eigenschaft RanToCompletion ist.This method creates a Task<TResult> object whose Task<TResult>.Result property is result and whose Status property is RanToCompletion. Die-Methode wird häufig verwendet, wenn der Rückgabewert einer Aufgabe sofort bekannt ist, ohne dass ein längerer Codepfad ausgeführt wird.The method is commonly used when the return value of a task is immediately known without executing a longer code path. Dies wird im Beispiel veranschaulicht.The example provides an illustration.

Zum Erstellen eines Task Objekts, das keinen Wert zurückgibt, rufen Sie das Task-Objekt aus der CompletedTask-Eigenschaft ab.To create a Task object that does not return a value, retrieve the Task object from the CompletedTask property.

Gilt für:

Siehe auch