Task<TResult>.Factory Propiedad

Definición

Proporciona acceso a métodos Factory Method para crear y configurar instancias de Task<TResult>.Provides access to factory methods for creating and configuring Task<TResult> instances.

public:
 static property System::Threading::Tasks::TaskFactory<TResult> ^ Factory { System::Threading::Tasks::TaskFactory<TResult> ^ get(); };
public static System.Threading.Tasks.TaskFactory<TResult> Factory { get; }
member this.Factory : System.Threading.Tasks.TaskFactory<'Result>
Public Shared ReadOnly Property Factory As TaskFactory(Of TResult)

Valor de propiedad

Un objeto de fábrica que puede crear una variedad de objetos Task<TResult>.A factory object that can create a variety of Task<TResult> objects.

Comentarios

Esta propiedad devuelve una instancia predeterminada de la TaskFactory<TResult> clase que es idéntica a la creada mediante una llamada al TaskFactory<TResult>.TaskFactory<TResult>() constructor sin parámetros.This property returns a default instance of the TaskFactory<TResult> class that is identical to the one created by calling the parameterless TaskFactory<TResult>.TaskFactory<TResult>() constructor. Tiene los siguientes valores de propiedad:It has the following property values:

Propiedad.Property ValorValue
TaskFactory<TResult>.CancellationToken CancellationToken.None
TaskFactory<TResult>.ContinuationOptions TaskContinuationOptions.None
TaskFactory<TResult>.CreationOptions TaskCreationOptions.None
TaskFactory<TResult>.Scheduler null, oTaskScheduler.Currentnull, or TaskScheduler.Current

El uso más común de esta propiedad es crear e iniciar una nueva tarea en una única llamada al TaskFactory<TResult>.StartNew método.The most common use of this property is to create and start a new task in a single call to the TaskFactory<TResult>.StartNew method.

Nota

A partir de Task.Run Task<TResult> , el método proporciona la forma más sencilla de crear un objeto con valores de configuración predeterminados. .NET Framework 4.5.NET Framework 4.5Starting with the .NET Framework 4.5.NET Framework 4.5, the Task.Run method provides the easiest way to create a Task<TResult> object with default configuration values.

En el ejemplo siguiente se usa Factory la propiedad estática para realizar tres llamadas TaskFactory<TResult>.StartNew al método.The following example uses the static Factory property to make three calls to the TaskFactory<TResult>.StartNew method. La primera inicia un Task<Int32> objeto, que ejecuta una expresión lambda que devuelve 1.The first starts a Task<Int32> object, which executes a lambda expression that returns 1. La segunda inicia un Task<Test> objeto, que ejecuta una expresión lambda que crea instancias de una nueva Test instancia de.The second starts a Task<Test> object, which executes a lambda expression that instantiates a new Test instance. El tercero inicia un Task<String[]> objeto, que enumera los archivos del directorio C:\Users\Public\Pictures\Sample imágenes .The third starts a Task<String[]> object, which enumerates the files in the C:\Users\Public\Pictures\Sample Pictures\ directory. (Tenga en cuenta que la ejecución correcta del ejemplo requiere que el directorio exista y que contenga archivos.(Note that successful execution of the example requires that the directory exist and that it contain files.

using System;
using System.Linq;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        // Return a value type with a lambda expression
        Task<int> task1 = Task<int>.Factory.StartNew(() => 1);
        int i = task1.Result;

        // Return a named reference type with a multi-line statement lambda.
        Task<Test> task2 = Task<Test>.Factory.StartNew(() =>
        {
            string s = ".NET";
            double d = 4.0;
            return new Test { Name = s, Number = d };
        });
        Test test = task2.Result;

        // Return an array produced by a PLINQ query
        Task<string[]> task3 = Task<string[]>.Factory.StartNew(() =>
        {
            string path = @"C:\Users\Public\Pictures\Sample Pictures\";
            string[] files = System.IO.Directory.GetFiles(path);

            var result = (from file in files.AsParallel()
                          let info = new System.IO.FileInfo(file)
                          where info.Extension == ".jpg"
                          select file).ToArray();

            return result;
        });

        foreach (var name in task3.Result)
            Console.WriteLine(name);

    }
    class Test
    {
        public string Name { get; set; }
        public double Number { get; set; }

    }
}
Imports System.Threading.Tasks

Module Module1

    Sub Main()
        ReturnAValue()

        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()

    End Sub

    Sub ReturnAValue()

        ' Return a value type with a lambda expression
        Dim task1 = Task(Of Integer).Factory.StartNew(Function() 1)
        Dim i As Integer = task1.Result

        ' Return a named reference type with a multi-line statement lambda.
        Dim task2 As Task(Of Test) = Task.Factory.StartNew(Function()
                                                               Dim s As String = ".NET"
                                                               Dim d As Integer = 4
                                                               Return New Test With {.Name = s, .Number = d}
                                                           End Function)

        Dim myTest As Test = task2.Result
        Console.WriteLine(myTest.Name & ": " & myTest.Number)

        ' Return an array produced by a PLINQ query.
        Dim task3 As Task(Of String())= Task(Of String()).Factory.StartNew(Function()

                                                           Dim path = "C:\Users\Public\Pictures\Sample Pictures\"
                                                           Dim files = System.IO.Directory.GetFiles(path)

                                                           Dim result = (From file In files.AsParallel()
                                                                Let info = New System.IO.FileInfo(file)
                                                                Where info.Extension = ".jpg"
                                                                Select file).ToArray()
                                                           Return result
                                                       End Function)

        For Each name As String In task3.Result
            Console.WriteLine(name)
        Next
    End Sub

    Class Test
        Public Name As String
        Public Number As Double
    End Class
End Module

Se aplica a

Consulte también: