TaskFactory.StartNew TaskFactory.StartNew TaskFactory.StartNew TaskFactory.StartNew Method

Definición

Crea e inicia un objeto Task.Creates and starts a Task.

Sobrecargas

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

Crea e inicia un objeto Task.Creates and starts a Task.

StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler)

Crea e inicia un objeto Task.Creates and starts a Task.

StartNew(Action<Object>, Object, TaskCreationOptions) StartNew(Action<Object>, Object, TaskCreationOptions) StartNew(Action<Object>, Object, TaskCreationOptions) StartNew(Action<Object>, Object, TaskCreationOptions)

Crea e inicia un objeto Task.Creates and starts a Task.

StartNew(Action<Object>, Object, CancellationToken) StartNew(Action<Object>, Object, CancellationToken) StartNew(Action<Object>, Object, CancellationToken)

Crea e inicia un objeto Task.Creates and starts a Task.

StartNew(Action, CancellationToken) StartNew(Action, CancellationToken) StartNew(Action, CancellationToken)

Crea e inicia un objeto Task.Creates and starts a Task.

StartNew(Action, TaskCreationOptions) StartNew(Action, TaskCreationOptions) StartNew(Action, TaskCreationOptions)

Crea e inicia un objeto Task.Creates and starts a Task.

StartNew(Action) StartNew(Action) StartNew(Action)

Crea e inicia una tarea.Creates and starts a task.

StartNew(Action<Object>, Object) StartNew(Action<Object>, Object) StartNew(Action<Object>, Object) StartNew(Action<Object>, Object)

Crea e inicia un objeto Task.Creates and starts a Task.

StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

StartNew<TResult>(Func<TResult>) StartNew<TResult>(Func<TResult>) StartNew<TResult>(Func<TResult>) StartNew<TResult>(Func<TResult>)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

StartNew<TResult>(Func<Object,TResult>, Object) StartNew<TResult>(Func<Object,TResult>, Object) StartNew<TResult>(Func<Object,TResult>, Object) StartNew<TResult>(Func<Object,TResult>, Object)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

StartNew<TResult>(Func<TResult>, CancellationToken) StartNew<TResult>(Func<TResult>, CancellationToken) StartNew<TResult>(Func<TResult>, CancellationToken)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

StartNew<TResult>(Func<TResult>, TaskCreationOptions) StartNew<TResult>(Func<TResult>, TaskCreationOptions) StartNew<TResult>(Func<TResult>, TaskCreationOptions) StartNew<TResult>(Func<TResult>, TaskCreationOptions)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken) StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken) StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions) StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions) StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions) StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

Comentarios

A partir de la .NET Framework 4.5.NET Framework 4.5, el Task.Run método es la manera recomendada para iniciar una tarea enlazada.Starting with the .NET Framework 4.5.NET Framework 4.5, the Task.Run method is the recommended way to launch a compute-bound task. Use el StartNew método solo cuando se requieren un control específico para una tarea de ejecución prolongada, enlazadas.Use the StartNew method only when you require fine-grained control for a long-running, compute-bound task. Esto incluye los escenarios en los que desea controlar lo siguiente:This includes scenarios in which you want to control the following:

  • Opciones de creación de la tarea.Task creation options. Las tareas creadas por el Task.Run método de forma predeterminada se crean con el TaskCreationOptions.DenyChildAttach opción.Tasks created by the Task.Run method by default are created with the TaskCreationOptions.DenyChildAttach option. Para invalidar este comportamiento, o proporcionar otros TaskCreationOptions opciones, llame a un StartNew de sobrecarga.To override this behavior, or to provide other TaskCreationOptions options, call a StartNew overload.

  • Paso de parámetros.Parameter passing. Las sobrecargas de los Task.Run método no le permiten pasar un parámetro para el delegado de la tarea.The overloads of the Task.Run method do not allow you to pass a parameter to the task delegate. Las sobrecargas de los StartNew método hacer.Overloads of the StartNew method do.

  • Programador de tareas.The task scheduler. Las sobrecargas de los Task.Run método usar el programador de tareas de forma predeterminada.The overloads of the Task.Run method use the default task scheduler. Para controlar el programador de tareas, llame a un StartNew sobrecarga con un scheduler parámetro.To control the task scheduler, call a StartNew overload with a scheduler parameter. Para obtener más información, vea TaskScheduler.For more information, see TaskScheduler.

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

Crea e inicia un objeto Task.Creates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task StartNew (Action<object> action, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);
member this.StartNew : Action<obj> * obj * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task

Parámetros

action
Action<Object>

Delegado de acción que se va a ejecutar de forma asincrónica.The action delegate to execute asynchronously.

state
Object Object Object Object

Objeto que contiene los datos que el delegado de action va a usar.An object containing data to be used by the action delegate.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar a la nueva tarea.The CancellationToken that will be assigned to the new task.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

Valor de TaskCreationOptions que controla el comportamiento del objeto Task creado.A TaskCreationOptions value that controls the behavior of the created Task

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se usa para programar el objeto Task creado.The TaskScheduler that is used to schedule the created Task.

Devoluciones

Objeto Task iniciado.The started Task.

Excepciones

La excepción que se produce cuando el argumento action es NULL.The exception that is thrown when the action argument is null.

O bien-or- La excepción que se produce cuando el argumento scheduler es NULL.The exception that is thrown when the scheduler argument is null.

La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. Para obtener más información, vea la sección Comentarios de FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions).For more information, see the Remarks for FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Comentarios

Llamar a StartNew equivale funcionalmente a la creación de una tarea mediante uno de sus constructores y, a continuación, que realiza la llamada Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea Task.Run vs Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler)

Crea e inicia un objeto Task.Creates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action ^ action, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task StartNew (Action action, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);
member this.StartNew : Action * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task

Parámetros

action
Action Action Action Action

Delegado de acción que se va a ejecutar de forma asincrónica.The action delegate to execute asynchronously.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar al nuevo objeto Task.The CancellationToken that will be assigned to the new Task

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

Valor de TaskCreationOptions que controla el comportamiento del objeto Task creado.A TaskCreationOptions value that controls the behavior of the created Task

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se usa para programar el objeto Task creado.The TaskScheduler that is used to schedule the created Task.

Devoluciones

Objeto Task iniciado.The started Task.

Excepciones

La excepción que se produce cuando el argumento action es NULL.The exception that is thrown when the action argument is null.

O bien-or- La excepción que se produce cuando el argumento scheduler es NULL.The exception that is thrown when the scheduler argument is null.

La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. Para obtener más información, vea la sección Comentarios de FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions).For more information, see the Remarks for FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Comentarios

Llamar a StartNew equivale funcionalmente a la creación de una tarea mediante uno de sus constructores y, a continuación, que realiza la llamada Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea Task.Run vs Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew(Action<Object>, Object, TaskCreationOptions) StartNew(Action<Object>, Object, TaskCreationOptions) StartNew(Action<Object>, Object, TaskCreationOptions) StartNew(Action<Object>, Object, TaskCreationOptions)

Crea e inicia un objeto Task.Creates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::Tasks::TaskCreationOptions creationOptions);
public System.Threading.Tasks.Task StartNew (Action<object> action, object state, System.Threading.Tasks.TaskCreationOptions creationOptions);
member this.StartNew : Action<obj> * obj * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task
Public Function StartNew (action As Action(Of Object), state As Object, creationOptions As TaskCreationOptions) As Task

Parámetros

action
Action<Object>

Delegado de acción que se va a ejecutar de forma asincrónica.The action delegate to execute asynchronously.

state
Object Object Object Object

Objeto que contiene los datos que el delegado de action va a usar.An object containing data to be used by the action delegate.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

Valor de TaskCreationOptions que controla el comportamiento del objeto Task creado.A TaskCreationOptions value that controls the behavior of the created Task

Devoluciones

Objeto Task iniciado.The started Task.

Excepciones

La excepción que se produce cuando el argumento action es NULL.The exception that is thrown when the action argument is null.

La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value.

Comentarios

Llamar a StartNew equivale funcionalmente a la creación de una tarea mediante uno de sus constructores y, a continuación, que realiza la llamada Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea Task.Run vs Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew(Action<Object>, Object, CancellationToken) StartNew(Action<Object>, Object, CancellationToken) StartNew(Action<Object>, Object, CancellationToken)

Crea e inicia un objeto Task.Creates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task StartNew (Action<object> action, object state, System.Threading.CancellationToken cancellationToken);
member this.StartNew : Action<obj> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task

Parámetros

action
Action<Object>

Delegado de acción que se va a ejecutar de forma asincrónica.The action delegate to execute asynchronously.

state
Object Object Object Object

Objeto que contiene los datos que el delegado de action va a usar.An object containing data to be used by the action delegate.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar al nuevo objeto Task.The CancellationToken that will be assigned to the new Task

Devoluciones

Objeto Task iniciado.The started Task.

Excepciones

La excepción que se produce cuando el argumento action es NULL.The exception that is thrown when the action argument is null.

Ejemplos

El ejemplo siguiente define una matriz de palabras de 6 letras.The following example defines an array of 6-letter words. Cada palabra, a continuación, se pasa a un Action<T> delegado, que codifica la palabra y muestra la palabra original y su versión alterada.Each word is then passed to an Action<T> delegate, which scrambles the word and displays the original word and its scrambled version.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      CancellationTokenSource cts = new CancellationTokenSource();
      CancellationToken token = cts.Token;
      var tasks = new List<Task>();
      Random rnd = new Random();
      Object lockObj = new Object();
      String[] words6 = { "reason", "editor", "rioter", "rental",
                          "senior", "regain", "ordain", "rained" };

      foreach (var word6 in words6)
         tasks.Add(Task.Factory.StartNew( (word) => { Char[] chars = word.ToString().ToCharArray();
                                                      double[] order = new double[chars.Length];
                                                      token.ThrowIfCancellationRequested();
                                                      bool wasZero = false;
                                                      lock (lockObj) {
                                                         for (int ctr = 0; ctr < order.Length; ctr++) {
                                                             order[ctr] = rnd.NextDouble();
                                                             if (order[ctr] == 0) {
                                                                if (! wasZero) {
                                                                   wasZero = true;
                                                                }
                                                                else {
                                                                   cts.Cancel();
                                                                }
                                                             }
                                                         }
                                                      }
                                                      token.ThrowIfCancellationRequested();
                                                      Array.Sort(order, chars);
                                                      Console.WriteLine("{0} --> {1}", word,
                                                                        new String(chars));
                                                    }, word6, token));

      try {
         Task.WaitAll(tasks.ToArray());
      }
      catch (AggregateException e) {
         foreach (var ie in e.InnerExceptions) {
            if (ie is OperationCanceledException) {
               Console.WriteLine("The word scrambling operation has been cancelled.");
               break;
            }
            else {
               Console.WriteLine(ie.GetType().Name + ": " + ie.Message);
            }
         }
      }
      finally {
         cts.Dispose();
      }
   }
}
// The example displays output like the following:
//    regain --> irnaeg
//    ordain --> rioadn
//    reason --> soearn
//    rained --> rinade
//    rioter --> itrore
//    senior --> norise
//    rental --> atnerl
//    editor --> oteird
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim cts As New CancellationTokenSource()
      Dim token As CancellationToken = cts.Token
      Dim tasks As New List(Of Task)()
      Dim rnd As New Random()
      Dim lockObj As New Object()
      Dim words6() As String = { "reason", "editor", "rioter", "rental",
                                 "senior", "regain", "ordain", "rained" }

      For Each word6 in words6
         tasks.Add(Task.Factory.StartNew( Sub(word)
                                              Dim chars() As Char = word.ToString().ToCharArray()
                                              Dim order(chars.Length - 1) As Double
                                              Dim wasZero As Boolean = False
                                              SyncLock lockObj
                                                 For ctr As Integer = 0 To order.Length - 1
                                                    order(ctr) = rnd.NextDouble()
                                                    If order(ctr) = 0 Then
                                                       If Not wasZero Then
                                                          wasZero = True
                                                       Else
                                                          cts.Cancel()
                                                       End If
                                                    End If
                                                 Next
                                              End SyncLock
                                              token.ThrowIfCancellationRequested()
                                              Array.Sort(order, chars)
                                              Console.WriteLine("{0} --> {1}", word,
                                                                new String(chars))
                                          End Sub, word6))
      Next
      Try
         Task.WaitAll(tasks.ToArray())
      Catch e As AggregateException
         For Each ie In e.InnerExceptions
            If TypeOf ie Is OperationCanceledException
               Console.WriteLine("The word scrambling operation has been cancelled.")
               Exit For
            Else
               Console.WriteLine(ie.GetType().Name + ": " + ie.Message)
            End If
         Next
      Finally
         cts.Dispose()
      End Try
   End Sub
End Module
' The example displays output like the following:
'       regain --> irnaeg
'       ordain --> rioadn
'       reason --> soearn
'       rained --> rinade
'       rioter --> itrore
'       senior --> norise
'       rental --> atnerl
'       editor --> oteird

Tenga en cuenta que en el ejemplo se inicializa un único generador de números aleatorios, que está protegido por un bloqueo.Note that the example initializes a single random number generator, which is protected by a lock. Para la necesidad de un bloqueo, vea "La System.Random clase y el subproceso de seguridad" en el Random tema de la clase.For the need of a lock, see "The System.Random class and thread safety" in the Random class topic. Para controlar la posibilidad de daños en el generador de números aleatorios, se pasa un token de cancelación para la tarea.To handle the possibility of corruption of the random number generator, a cancellation token is passed to task. Si dos números aleatorios igual a cero, el método supone que el generador de números aleatorios está dañado y establece el token de cancelación.If two random numbers equal zero, the method assumes that the random number generator is corrupted and sets the cancellation token. Antes de ordenar la chars matriz que contiene los seis caracteres de una palabra, las llamadas al método el CancellationToken.ThrowIfCancellationRequested método inicie una OperationCanceledException si se ha cancelado el token.Before sorting the chars array that contains the six characters in a word, the method calls the CancellationToken.ThrowIfCancellationRequested method to throw an OperationCanceledException if the token has been canceled.

Comentarios

Llamar a StartNew equivale funcionalmente a la creación de una tarea mediante uno de sus constructores y, a continuación, que realiza la llamada Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea Task.Run vs Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew(Action, CancellationToken) StartNew(Action, CancellationToken) StartNew(Action, CancellationToken)

Crea e inicia un objeto Task.Creates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action ^ action, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task StartNew (Action action, System.Threading.CancellationToken cancellationToken);
member this.StartNew : Action * System.Threading.CancellationToken -> System.Threading.Tasks.Task

Parámetros

action
Action Action Action Action

Delegado de acción que se va a ejecutar de forma asincrónica.The action delegate to execute asynchronously.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar a la nueva tarea.The CancellationToken that will be assigned to the new task.

Devoluciones

Objeto Task iniciado.The started Task.

Excepciones

La excepción que se produce cuando el argumento action es NULL.The exception that is thrown when the action argument is null.

Ejemplos

El ejemplo siguiente se llama el StartNew(Action, CancellationToken) método para crear una tarea que recorre en iteración los archivos en el directorio C:\Windows\System32.The following example calls the StartNew(Action, CancellationToken) method to create a task that iterates the files in the C:\Windows\System32 directory. La expresión lambda llama el Parallel.ForEach método para agregar información acerca de cada archivo a un List<T> objeto.The lambda expression calls the Parallel.ForEach method to add information about each file to a List<T> object. Cada uno separa la tarea anidada que se invoca el Parallel.ForEach bucle comprueba el estado del token de cancelación y, si se solicita la cancelación, llama a la CancellationToken.ThrowIfCancellationRequested método.Each detached nested task invoked by the Parallel.ForEach loop checks the state of the cancellation token and, if cancellation is requested, calls the CancellationToken.ThrowIfCancellationRequested method. El CancellationToken.ThrowIfCancellationRequested método produce una OperationCanceledException excepción que se controla en un catch bloquear cuando el subproceso que realiza la llamada llama a la Task.Wait método.The CancellationToken.ThrowIfCancellationRequested method throws an OperationCanceledException exception that is handled in a catch block when the calling thread calls the Task.Wait method.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tokenSource = new CancellationTokenSource();
      var token = tokenSource.Token;
      var files = new List<Tuple<string, string, long, DateTime>>();

      var t = Task.Factory.StartNew( () => { string dir = "C:\\Windows\\System32\\";
                                object obj = new Object();
                                if (Directory.Exists(dir)) {
                                   Parallel.ForEach(Directory.GetFiles(dir),
                                   f => {
                                           if (token.IsCancellationRequested)
                                              token.ThrowIfCancellationRequested();
                                           var fi = new FileInfo(f);
                                           lock(obj) {
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc));          
                                           }
                                      });
                                 }
                              }
                        , token);
      tokenSource.Cancel();
      try {
         t.Wait(); 
         Console.WriteLine("Retrieved information for {0} files.", files.Count);
      }
      catch (AggregateException e) {
         Console.WriteLine("Exception messages:");
         foreach (var ie in e.InnerExceptions)
            Console.WriteLine("   {0}: {1}", ie.GetType().Name, ie.Message);

         Console.WriteLine("\nTask status: {0}", t.Status);       
      }
      finally {
         tokenSource.Dispose();
      }
   }
}
// The example displays the following output:
//       Exception messages:
//          TaskCanceledException: A task was canceled.
//       
//       Task status: Canceled
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tokenSource As New CancellationTokenSource()
      Dim token As CancellationToken = tokenSource.Token
      Dim files As New List(Of Tuple(Of String, String, Long, Date))()

      Dim t As Task = Task.Factory.StartNew( Sub()
                                   Dim dir As String = "C:\Windows\System32\"
                                   Dim obj As New Object()
                                   If Directory.Exists(dir)Then
                                      Parallel.ForEach(Directory.GetFiles(dir), 
                                         Sub(f)
                                            If token.IsCancellationRequested Then
                                               token.ThrowIfCancellationRequested()
                                            End If  
                                            Dim fi As New FileInfo(f)
                                            SyncLock(obj)
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc))          
                                            End SyncLock
                                         End Sub)
                                   End If
                                End Sub, token)
      tokenSource.Cancel()
      Try
         t.Wait() 
         Console.WriteLine("Retrieved information for {0} files.", files.Count)
      Catch e As AggregateException
         Console.WriteLine("Exception messages:")
         For Each ie As Exception In e.InnerExceptions
            Console.WriteLine("   {0}:{1}", ie.GetType().Name, ie.Message)
         Next
         Console.WriteLine()
         Console.WriteLine("Task status: {0}", t.Status)       
      Finally
         tokenSource.Dispose()
      End Try
   End Sub
End Module
' The example displays the following output:
'       Exception messages:
'          TaskCanceledException: A task was canceled.
'       
'       Task status: Canceled

Comentarios

Una llamada a StartNew es funcionalmente equivalente a la creación de una tarea mediante uno de sus constructores y, a continuación, que realiza la llamada Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Task.Run(Action, CancellationToken) método como una forma rápida para llamar a StartNew(Action, CancellationToken) con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Task.Run(Action, CancellationToken) method as a quick way to call StartNew(Action, CancellationToken) with default parameters. Sin embargo, tenga en cuenta que hay una diferencia de comportamiento entre los dos métodos relacionados con: Task.Run(Action, CancellationToken) de forma predeterminada no permite secundarios tareas iniciadas con el TaskCreationOptions.AttachedToParent opción para adjuntar a la actual Task de instancia, mientras que StartNew(Action, CancellationToken) does.Note, however, that there is a difference in behavior between the two methods regarding : Task.Run(Action, CancellationToken) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task instance, whereas StartNew(Action, CancellationToken) does. Para obtener más información y ejemplos de código, vea Task.Run vs Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew(Action, TaskCreationOptions) StartNew(Action, TaskCreationOptions) StartNew(Action, TaskCreationOptions)

Crea e inicia un objeto Task.Creates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action ^ action, System::Threading::Tasks::TaskCreationOptions creationOptions);
public System.Threading.Tasks.Task StartNew (Action action, System.Threading.Tasks.TaskCreationOptions creationOptions);
member this.StartNew : Action * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task

Parámetros

action
Action Action Action Action

Delegado de acción que se va a ejecutar de forma asincrónica.The action delegate to execute asynchronously.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

Valor de TaskCreationOptions que controla el comportamiento del objeto Task creado.A TaskCreationOptions value that controls the behavior of the created Task

Devoluciones

Objeto Task iniciado.The started Task.

Excepciones

La excepción que se produce cuando el argumento action es NULL.The exception that is thrown when the action argument is null.

La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value.

Comentarios

Llamar a StartNew equivale funcionalmente a la creación de una tarea mediante uno de sus constructores y, a continuación, que realiza la llamada Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea Task.Run vs Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew(Action) StartNew(Action) StartNew(Action)

Crea e inicia una tarea.Creates and starts a task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action ^ action);
public System.Threading.Tasks.Task StartNew (Action action);
member this.StartNew : Action -> System.Threading.Tasks.Task

Parámetros

action
Action Action Action Action

Delegado de acción que se va a ejecutar de forma asincrónica.The action delegate to execute asynchronously.

Devoluciones

La tarea iniciada.The started task.

Excepciones

El argumento action es null.The action argument is null.

Ejemplos

En el ejemplo siguiente se usa el StartNew(Action) método que se invoca varias veces un Action delegado que genera un número aleatorio, lo interpreta como un punto de código Unicode, lo convierte en una unidad de código UTF16 codificado y muestra información sobre el resultado carácter o caracteres.The following example uses the StartNew(Action) method to repeatedly invoke an Action delegate that generates a random number, interprets it as a Unicode code point, converts it to a UTF16-encoded code unit, and displays information about the resulting character or characters.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      List<Task> tasks  = new List<Task>();
      // Execute the task 10 times.
      for (int ctr = 1; ctr <= 9; ctr++) {
         tasks.Add(Task.Factory.StartNew( () => {
                                            int utf32 = 0;
                                            lock(rnd) {
                                               // Get UTF32 value.
                                               utf32 = rnd.Next(0, 0xE01F0);
                                            }
                                            // Convert it to a UTF16-encoded character.
                                            string utf16 = Char.ConvertFromUtf32(utf32);
                                            // Display information about the character.
                                            Console.WriteLine("0x{0:X8} --> '{1,2}' ({2})", 
                                                              utf32, utf16, ShowHex(utf16));
                                         }));                           
      }
      Task.WaitAll(tasks.ToArray()); 
   }

   private static string ShowHex(string value)
   {
      string hexString = null;
      // Handle only non-control characters.
      if (! Char.IsControl(value, 0)) {
         foreach (var ch in value)
            hexString += String.Format("0x{0} ", Convert.ToUInt16(ch));

      }   
      return hexString.Trim();
   }
}
// The example displays the following output:
//       0x00097103 --> '����' (0x55836 0x56579)
//       0x000A98A1 --> '����' (0x55910 0x56481)
//       0x00050002 --> '����' (0x55552 0x56322)
//       0x0000FEF1 --> ' ﻱ' (0x65265)
//       0x0008BC0A --> '����' (0x55791 0x56330)
//       0x000860EA --> '����' (0x55768 0x56554)
//       0x0009AC5A --> '����' (0x55851 0x56410)
//       0x00053320 --> '����' (0x55564 0x57120)
//       0x000874EF --> '����' (0x55773 0x56559)
Imports System.Collections.Generic
Imports System.Threading.Tasks

Public Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim tasks As New List(Of Task)
      ' Execute the task 10 times.
      For ctr As Integer = 1 To 9
         tasks.Add(Task.Factory.StartNew(Sub()
                                            Dim utf32 As Integer
                                            SyncLock(rnd)
                                               ' Get UTF32 value.
                                               utf32 = rnd.Next(0, &hE01F0)
                                            End SyncLock
                                            ' Convert it to a UTF16-encoded character.
                                            Dim utf16 As String = Char.ConvertFromUtf32(utf32)
                                            ' Display information about the character.
                                            Console.WriteLine("0x{0:X8} --> '{1,2}' ({2})", 
                                                              utf32, utf16, ShowHex(utf16))
                                         End Sub))                           
      Next
      Task.WaitAll(tasks.ToArray()) 
   End Sub
   
   Private Function ShowHex(value As String) As String
      Dim hexString As String = Nothing
      ' Handle only non-control characters.
      If Not Char.IsControl(value, 0) Then
         For Each ch In value
            hexString += String.Format("0x{0} ", Convert.ToUInt16(ch))
         Next
      End If   
      Return hexString.Trim()
   End Function
End Module
' The example displays output similar to the following:
'       0x00097103 --> '����' (0x55836 0x56579)
'       0x000A98A1 --> '����' (0x55910 0x56481)
'       0x00050002 --> '����' (0x55552 0x56322)
'       0x0000FEF1 --> ' ﻱ' (0x65265)
'       0x0008BC0A --> '����' (0x55791 0x56330)
'       0x000860EA --> '����' (0x55768 0x56554)
'       0x0009AC5A --> '����' (0x55851 0x56410)
'       0x00053320 --> '����' (0x55564 0x57120)
'       0x000874EF --> '����' (0x55773 0x56559)

Comentarios

Una llamada a StartNew es funcionalmente equivalente a la creación de una tarea mediante uno de sus constructores y, a continuación, llamar a la Task.Start método para programar la tarea para su ejecución.Calling StartNew is functionally equivalent to creating a task by using one of its constructors, and then calling the Task.Start method to schedule the task for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Task.Run(Action) método como una forma rápida para llamar a StartNew(Action) con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Task.Run(Action) method as a quick way to call StartNew(Action) with default parameters. Sin embargo, tenga en cuenta que hay una diferencia de comportamiento entre los dos métodos relacionados con: Task.Run(Action) de forma predeterminada no permite secundarios tareas iniciadas con el TaskCreationOptions.AttachedToParent opción para adjuntar a la actual Task de instancia, mientras que StartNew(Action) does.Note, however, that there is a difference in behavior between the two methods regarding : Task.Run(Action) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task instance, whereas StartNew(Action) does. Para obtener más información y ejemplos de código, vea Task.Run vs Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew(Action<Object>, Object) StartNew(Action<Object>, Object) StartNew(Action<Object>, Object) StartNew(Action<Object>, Object)

Crea e inicia un objeto Task.Creates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action<System::Object ^> ^ action, System::Object ^ state);
public System.Threading.Tasks.Task StartNew (Action<object> action, object state);
member this.StartNew : Action<obj> * obj -> System.Threading.Tasks.Task
Public Function StartNew (action As Action(Of Object), state As Object) As Task

Parámetros

action
Action<Object>

Delegado de acción que se va a ejecutar de forma asincrónica.The action delegate to execute asynchronously.

state
Object Object Object Object

Objeto que contiene los datos que el delegado de action va a usar.An object containing data to be used by the action delegate.

Devoluciones

Objeto Task iniciado.The started Task.

Excepciones

El argumento action es null.The action argument is null.

Ejemplos

El ejemplo siguiente define una matriz de palabras de 6 letras.The following example defines an array of 6-letter words. Cada palabra, a continuación, se pasa a un Action<T> delegado, que codifica la palabra y muestra la palabra original y su versión alterada.Each word is then passed to an Action<T> delegate, which scrambles the word and displays the original word and its scrambled version.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tasks = new List<Task>();
      Random rnd = new Random();
      Object lockObj = new Object();
      String[] words6 = { "reason", "editor", "rioter", "rental",
                          "senior", "regain", "ordain", "rained" };

      foreach (var word6 in words6)
         tasks.Add(Task.Factory.StartNew( (word) => { Char[] chars = word.ToString().ToCharArray();
                                                      double[] order = new double[chars.Length];
                                                      lock (lockObj) {
                                                         for (int ctr = 0; ctr < order.Length; ctr++)
                                                             order[ctr] = rnd.NextDouble();
                                                      }
                                                      Array.Sort(order, chars);
                                                      Console.WriteLine("{0} --> {1}", word,
                                                                        new String(chars));
                                                    }, word6));

      Task.WaitAll(tasks.ToArray());
   }
}
// The example displays output like the following:
//    regain --> irnaeg
//    ordain --> rioadn
//    reason --> soearn
//    rained --> rinade
//    rioter --> itrore
//    senior --> norise
//    rental --> atnerl
//    editor --> oteird
Imports System.Collections.Generic
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks As New List(Of Task)()
      Dim rnd As New Random()
      Dim lockObj As New Object()
      Dim words6() As String = { "reason", "editor", "rioter", "rental",
                                 "senior", "regain", "ordain", "rained" }

      For Each word6 in words6
         tasks.Add(Task.Factory.StartNew( Sub(word)
                                              Dim chars() As Char = word.ToString().ToCharArray()
                                              Dim order(chars.Length - 1) As Double
                                              SyncLock lockObj
                                                 For ctr As Integer = 0 To order.Length - 1
                                                    order(ctr) = rnd.NextDouble()
                                                 Next
                                              End SyncLock
                                              Array.Sort(order, chars)
                                              Console.WriteLine("{0} --> {1}", word,
                                                                new String(chars))
                                          End Sub, word6))
      Next
      Task.WaitAll(tasks.ToArray())
   End Sub
End Module
' The example displays output like the following:
'       regain --> irnaeg
'       ordain --> rioadn
'       reason --> soearn
'       rained --> rinade
'       rioter --> itrore
'       senior --> norise
'       rental --> atnerl
'       editor --> oteird

Tenga en cuenta que en el ejemplo se inicializa un único generador de números aleatorios, que está protegido por un bloqueo.Note that the example initializes a single random number generator, which is protected by a lock. Para la necesidad de un bloqueo, vea "La System.Random clase y el subproceso de seguridad" en el Random tema de la clase.For the need of a lock, see "The System.Random class and thread safety" in the Random class topic.

Comentarios

Una llamada a StartNew es funcionalmente equivalente a la creación de un Task utilizando uno de sus constructores y, a continuación, llamar a la Start método para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling the Start method to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea Task.Run vs Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<TResult> ^ function, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);
member this.StartNew : Func<'Result> * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task<'Result>

Parámetros de tipo

TResult

Tipo del resultado que está disponible a través de Task<TResult>.The type of the result available through the Task<TResult>.

Parámetros

function
Func<TResult> Func<TResult> Func<TResult> Func<TResult>

Delegado de función que devuelve el resultado futuro que va a estar disponible a través de Task<TResult>.A function delegate that returns the future result to be available through the Task<TResult>.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar a la nueva tarea.The CancellationToken that will be assigned to the new task.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

Valor de TaskCreationOptions que controla el comportamiento del objeto Task<TResult> creado.A TaskCreationOptions value that controls the behavior of the created Task<TResult>.

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se usa para programar el objeto Task<TResult> creado.The TaskScheduler that is used to schedule the created Task<TResult>.

Devoluciones

Excepciones

La excepción que se produce cuando el argumento function es NULL.The exception that is thrown when the function argument is null.

O bien-or- La excepción que se produce cuando el argumento scheduler es NULL.The exception that is thrown when the scheduler argument is null.

La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. Para obtener más información, vea la sección Comentarios de FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions).For more information, see the Remarks for FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Comentarios

Llamar a StartNew equivale funcionalmente a la creación de un Task<TResult> utilizando uno de sus constructores y, a continuación, llamar a Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea la entrada Task.Run vs. Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew<TResult>(Func<TResult>) StartNew<TResult>(Func<TResult>) StartNew<TResult>(Func<TResult>) StartNew<TResult>(Func<TResult>)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<TResult> ^ function);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function);
member this.StartNew : Func<'Result> -> System.Threading.Tasks.Task<'Result>
Public Function StartNew(Of TResult) (function As Func(Of TResult)) As Task(Of TResult)

Parámetros de tipo

TResult

Tipo del resultado que está disponible a través de Task<TResult>.The type of the result available through the Task<TResult>.

Parámetros

function
Func<TResult> Func<TResult> Func<TResult> Func<TResult>

Delegado de función que devuelve el resultado futuro que va a estar disponible a través de Task<TResult>.A function delegate that returns the future result to be available through the Task<TResult>.

Devoluciones

Excepciones

El argumento function es null.The function argument is null.

Ejemplos

El ejemplo siguiente es una aplicación de adición simple que genera dos números aleatorios y pide al usuario que escriba su suma.The following example is a simple addition app that generates two random numbers and prompts the user to enter their sum. A continuación, indica si la respuesta es correcta o, si la respuesta del usuario no es un número válido, pide al usuario que vuelva a escribir un número válido.It then indicates whether the answer is correct or, if the user's response is not a valid number, prompts the user to re-enter a valid number. El StartNew se usa para crear el Task<TResult> los objetos que devuelven los números aleatorios para agregar.The StartNew is used to create the Task<TResult> objects that return the random numbers to add.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      Task<int>[] tasks = new Task<int>[2];
      Object obj = new Object();
      
      while (true) {
         for (int ctr = 0; ctr <= 1; ctr++)
            tasks[ctr] = Task.Factory.StartNew(() => { int i = 0;
                                                       lock(obj) {
                                                          i = rnd.Next(101);
                                                       }
                                                       return i; });

         Task.WaitAll(tasks);
         int n1 = tasks[0].Result;
         int n2 = tasks[1].Result;
         int result = n1 + n2;
         bool validInput = false;
         while (! validInput) {
            ShowMessage(n1, n2);
            string userInput = Console.ReadLine();
            // Process user input.
            if (userInput.Trim().ToUpper() == "X") return;
            int answer;
            validInput = Int32.TryParse(userInput, out answer);
            if (! validInput)
               Console.WriteLine("Invalid input. Try again, but enter only numbers. ");
            else if (answer == result)
               Console.WriteLine("Correct!");
            else
               Console.WriteLine("Incorrect. The correct answer is {0}.", result);
         }
      }
   }

   private static void ShowMessage(int n1, int n2)
   {
      Console.WriteLine("\nEnter 'x' to exit...");
      Console.Write("{0} + {1} = ", n1, n2);
   }
}
// The example displays the following output:
//       Enter 'x' to exit...
//       15 + 11 = 26
//       Correct!
//
//       Enter 'x' to exit...
//       75 + 33 = adc
//       Invalid input. Try again, but enter only numbers.
//
//       Enter 'x' to exit...
//       75 + 33 = 108
//       Correct!
//
//       Enter 'x' to exit...
//       67 + 55 = 133
//       Incorrect. The correct answer is 122.
//
//       Enter 'x' to exit...
//       92 + 51 = 133
//       Incorrect. The correct answer is 143.
//
//       Enter 'x' to exit...
//       81 + 65 = x
   
Imports System.Threading.Tasks

Module AdditionTester
   Public Sub Main()
      Dim rnd As New Random()
      Dim tasks(1) As Task(Of Integer)
      Dim obj As New Object()
      
      Do While True
         For ctr As Integer = 0 To 1
            tasks(ctr) = Task.Factory.StartNew(Function()
                                                  Dim i As Integer
                                                  SyncLock(obj)
                                                     i = rnd.Next(101)
                                                  End SyncLock
                                                  Return i
                                               End Function)
         Next
         Task.WaitAll(tasks)
         Dim n1 As Integer = tasks(0).Result
         Dim n2 As Integer = tasks(1).Result
         Dim result As Integer = n1 + n2
         Dim validInput As Boolean = False
         Do While Not validInput
            ShowMessage(n1, n2)
            Dim userInput As String = Console.ReadLine()
            ' Process user input.
            If userInput.Trim().ToUpper = "X" Then Exit Sub
            Dim answer As Integer
            validInput = Int32.TryParse(userInput, answer)
            If Not validInput Then
               Console.WriteLine("Invalid input. Try again, but enter only numbers. ")
            Else If answer = result Then
               Console.WriteLine("Correct!")
            Else
               Console.WriteLine("Incorrect. The correct answer is {0}.", result)
            End If
         Loop
      Loop
   End Sub
   
   Private Sub ShowMessage(n1 As Integer, n2 As Integer)
      Console.WriteLine()
      Console.WriteLine("Enter 'x' to exit...")
      Console.Write("{0} + {1} = ", n1, n2)
   End Sub
End Module
' The example displays output like the following:
'       Enter 'x' to exit...
'       15 + 11 = 26
'       Correct!
'
'       Enter 'x' to exit...
'       75 + 33 = adc
'       Invalid input. Try again, but enter only numbers.
'
'       Enter 'x' to exit...
'       75 + 33 = 108
'       Correct!
'
'       Enter 'x' to exit...
'       67 + 55 = 133
'       Incorrect. The correct answer is 122.
'
'       Enter 'x' to exit...
'       92 + 51 = 133
'       Incorrect. The correct answer is 143.
'
'       Enter 'x' to exit...
'       81 + 65 = x

Comentarios

Una llamada a StartNew es funcionalmente equivalente a la creación de un Task<TResult> utilizando uno de sus constructores y, a continuación, llamar a Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede llamar a la Task.Run<TResult>(Func<TResult>) método como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can call the Task.Run<TResult>(Func<TResult>) method as a quick way to call StartNew with default parameters. Sin embargo, tenga en cuenta que hay una diferencia de comportamiento entre los dos métodos relacionados con: Task.Run<TResult>(Func<TResult>) de forma predeterminada no permite secundarios tareas iniciadas con el TaskCreationOptions.AttachedToParent opción para adjuntar a la actual Task<TResult> de instancia, mientras que StartNew<TResult>(Func<TResult>) does.Note, however, that there is a difference in behavior between the two methods regarding : Task.Run<TResult>(Func<TResult>) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task<TResult> instance, whereas StartNew<TResult>(Func<TResult>) does. Para obtener más información y ejemplos de código, vea la entrada Task.Run vs. Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew<TResult>(Func<Object,TResult>, Object) StartNew<TResult>(Func<Object,TResult>, Object) StartNew<TResult>(Func<Object,TResult>, Object) StartNew<TResult>(Func<Object,TResult>, Object)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<System::Object ^, TResult> ^ function, System::Object ^ state);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state);
member this.StartNew : Func<obj, 'Result> * obj -> System.Threading.Tasks.Task<'Result>
Public Function StartNew(Of TResult) (function As Func(Of Object, TResult), state As Object) As Task(Of TResult)

Parámetros de tipo

TResult

Tipo del resultado que está disponible a través de Task<TResult>.The type of the result available through the Task<TResult>.

Parámetros

function
Func<Object,TResult>

Delegado de función que devuelve el resultado futuro que va a estar disponible a través de Task<TResult>.A function delegate that returns the future result to be available through the Task<TResult>.

state
Object Object Object Object

Objeto que contiene los datos que el delegado de function va a usar.An object containing data to be used by the function delegate.

Devoluciones

Excepciones

La excepción que se produce cuando el argumento function es NULL.The exception that is thrown when the function argument is null.

Comentarios

Llamar a StartNew equivale funcionalmente a la creación de un Task<TResult> utilizando uno de sus constructores y, a continuación, llamar a Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea la entrada Task.Run vs. Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew<TResult>(Func<TResult>, CancellationToken) StartNew<TResult>(Func<TResult>, CancellationToken) StartNew<TResult>(Func<TResult>, CancellationToken)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<TResult> ^ function, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function, System.Threading.CancellationToken cancellationToken);
member this.StartNew : Func<'Result> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>

Parámetros de tipo

TResult

Tipo del resultado que está disponible a través de Task<TResult>.The type of the result available through the Task<TResult>.

Parámetros

function
Func<TResult> Func<TResult> Func<TResult> Func<TResult>

Delegado de función que devuelve el resultado futuro que va a estar disponible a través de Task<TResult>.A function delegate that returns the future result to be available through the Task<TResult>.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar al nuevo objeto Task.The CancellationToken that will be assigned to the new Task

Devoluciones

Excepciones

La excepción que se produce cuando el argumento function es NULL.The exception that is thrown when the function argument is null.

Ejemplos

El ejemplo siguiente utiliza dos tareas para calcular la secuencia de Fibonacci terminan en F100 = F100 1 + F100-2 con los valores de inicialización F1 = 1, F2 = 1 y F1 = 0, F2 = 1.The following example uses two tasks to compute the Fibonacci sequence ending in F100 = F100-1 + F100-2 with seed values F1= 1, F2 = 1 and F1 = 0, F2= 1. Aproximadamente la mitad del tiempo, un token de cancelación se establece como las operaciones de ejecución.Approximately half of the time, a cancellation token is set as the operations execute. El resultado del ejemplo muestra el resultado si las dos tareas se completen correctamente y si se cancela el token.The output from the example shows the result if the two tasks complete successfully and if the token is cancelled.

using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var rnd = new Random();
      var tasks = new List<Task<BigInteger[]>>();
      var source = new CancellationTokenSource();
      var token = source.Token;
      for (int ctr = 0; ctr <= 1; ctr++) {
         int start = ctr;
         tasks.Add(Task.Run( () => { BigInteger[] sequence = new BigInteger[100];
                                     sequence[0] = start;
                                     sequence[1] = 1;
                                     for (int index = 2; index <= sequence.GetUpperBound(0); index++) {
                                        token.ThrowIfCancellationRequested();
                                        sequence[index] = sequence[index - 1] + sequence[index - 2];
                                     }
                                     return sequence;
                                   }, token));
      }
      if (rnd.Next(0, 2) == 1)
         source.Cancel();
      try {
         Task.WaitAll(tasks.ToArray());
         foreach (var t in tasks)
            Console.WriteLine("{0}, {1}...{2:N0}", t.Result[0], t.Result[1],
                              t.Result[99]);
      }
      catch (AggregateException e) {
         foreach (var ex in e.InnerExceptions)
            Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message);
      }
   }
}
// The example displays either the following output:
//    0, 1...218,922,995,834,555,169,026
//    1, 1...354,224,848,179,261,915,075
// or the following output:
//    TaskCanceledException: A task was canceled.
//    TaskCanceledException: A task was canceled.
Imports System.Collections.Generic
Imports System.Numerics
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim tasks As New List(Of Task(Of BigInteger()))
      Dim source As New CancellationTokenSource
      Dim token As CancellationToken = source.Token
      For ctr As Integer = 0 To 1
         Dim start As Integer = ctr
         tasks.Add(Task.Run(Function()
                               Dim sequence(99) As BigInteger
                               sequence(0) = start
                               sequence(1) = 1
                               For index As Integer = 2 To sequence.GetUpperBound(0)
                                  token.ThrowIfCancellationRequested()
                                  sequence(index) = sequence(index - 1) + sequence(index - 2)
                               Next
                               Return sequence
                            End Function, token))
      Next
      If rnd.Next(0, 2) = 1 Then source.Cancel
      Try
         Task.WaitAll(tasks.ToArray())
         For Each t In tasks
            Console.WriteLine("{0}, {1}...{2:N0}", t.Result(0), t.Result(1),
                              t.Result(99))
         Next
      Catch e As AggregateException
         For Each ex In e.InnerExceptions
            Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message)
         Next
      End Try
   End Sub
End Module
' The example displays either the following output:
'    0, 1...218,922,995,834,555,169,026
'    1, 1...354,224,848,179,261,915,075
' or the following output:
'    TaskCanceledException: A task was canceled.
'    TaskCanceledException: A task was canceled.

Comentarios

Una llamada a StartNew es funcionalmente equivalente a la creación de un Task<TResult> utilizando uno de sus constructores y, a continuación, llamar a Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Task.Run<TResult>(Func<TResult>, CancellationToken) método como una forma rápida para llamar a StartNew<TResult>(Func<TResult>, CancellationToken) con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Task.Run<TResult>(Func<TResult>, CancellationToken) method as a quick way to call StartNew<TResult>(Func<TResult>, CancellationToken) with default parameters. Sin embargo, tenga en cuenta que hay una diferencia de comportamiento entre los dos métodos relacionados con: Task.Run<TResult>(Func<TResult>, CancellationToken) de forma predeterminada no permite secundarios tareas iniciadas con el TaskCreationOptions.AttachedToParent opción para adjuntar a la actual Task<TResult> de instancia, mientras que StartNew<TResult>(Func<TResult>, CancellationToken) does.Note, however, that there is a difference in behavior between the two methods regarding : Task.Run<TResult>(Func<TResult>, CancellationToken) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task<TResult> instance, whereas StartNew<TResult>(Func<TResult>, CancellationToken) does. Para obtener más información y ejemplos de código, vea la entrada Task.Run vs. Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew<TResult>(Func<TResult>, TaskCreationOptions) StartNew<TResult>(Func<TResult>, TaskCreationOptions) StartNew<TResult>(Func<TResult>, TaskCreationOptions) StartNew<TResult>(Func<TResult>, TaskCreationOptions)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<TResult> ^ function, System::Threading::Tasks::TaskCreationOptions creationOptions);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function, System.Threading.Tasks.TaskCreationOptions creationOptions);
member this.StartNew : Func<'Result> * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
Public Function StartNew(Of TResult) (function As Func(Of TResult), creationOptions As TaskCreationOptions) As Task(Of TResult)

Parámetros de tipo

TResult

Tipo del resultado que está disponible a través de Task<TResult>.The type of the result available through the Task<TResult>.

Parámetros

function
Func<TResult> Func<TResult> Func<TResult> Func<TResult>

Delegado de función que devuelve el resultado futuro que va a estar disponible a través de Task<TResult>.A function delegate that returns the future result to be available through the Task<TResult>.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

Valor de TaskCreationOptions que controla el comportamiento del objeto Task<TResult> creado.A TaskCreationOptions value that controls the behavior of the created Task<TResult>.

Devoluciones

Excepciones

La excepción que se produce cuando el argumento function es NULL.The exception that is thrown when the function argument is null.

La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. Para obtener más información, vea la sección Comentarios de FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions).For more information, see the Remarks for FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Comentarios

Llamar a StartNew equivale funcionalmente a la creación de un Task<TResult> utilizando uno de sus constructores y, a continuación, llamar a Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea la entrada Task.Run vs. Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken) StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken) StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state, System.Threading.CancellationToken cancellationToken);
member this.StartNew : Func<obj, 'Result> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>

Parámetros de tipo

TResult

Tipo del resultado que está disponible a través de Task<TResult>.The type of the result available through the Task<TResult>.

Parámetros

function
Func<Object,TResult>

Delegado de función que devuelve el resultado futuro que va a estar disponible a través de Task<TResult>.A function delegate that returns the future result to be available through the Task<TResult>.

state
Object Object Object Object

Objeto que contiene los datos que el delegado de function va a usar.An object containing data to be used by the function delegate.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar al nuevo objeto Task.The CancellationToken that will be assigned to the new Task

Devoluciones

Excepciones

La excepción que se produce cuando el argumento function es NULL.The exception that is thrown when the function argument is null.

Comentarios

Llamar a StartNew equivale funcionalmente a la creación de un Task<TResult> utilizando uno de sus constructores y, a continuación, llamar a Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea la entrada Task.Run vs. Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions) StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions) StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions) StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::Tasks::TaskCreationOptions creationOptions);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state, System.Threading.Tasks.TaskCreationOptions creationOptions);
member this.StartNew : Func<obj, 'Result> * obj * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
Public Function StartNew(Of TResult) (function As Func(Of Object, TResult), state As Object, creationOptions As TaskCreationOptions) As Task(Of TResult)

Parámetros de tipo

TResult

Tipo del resultado que está disponible a través de Task<TResult>.The type of the result available through the Task<TResult>.

Parámetros

function
Func<Object,TResult>

Delegado de función que devuelve el resultado futuro que va a estar disponible a través de Task<TResult>.A function delegate that returns the future result to be available through the Task<TResult>.

state
Object Object Object Object

Objeto que contiene los datos que el delegado de function va a usar.An object containing data to be used by the function delegate.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

Valor de TaskCreationOptions que controla el comportamiento del objeto Task<TResult> creado.A TaskCreationOptions value that controls the behavior of the created Task<TResult>.

Devoluciones

Excepciones

La excepción que se produce cuando el argumento function es NULL.The exception that is thrown when the function argument is null.

La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. Para obtener más información, vea la sección Comentarios de FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions).For more information, see the Remarks for FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Comentarios

Llamar a StartNew equivale funcionalmente a la creación de un Task<TResult> utilizando uno de sus constructores y, a continuación, llamar a Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea la entrada Task.Run vs. Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

Crea e inicia un objeto Task<TResult>.Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);
member this.StartNew : Func<obj, 'Result> * obj * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task<'Result>

Parámetros de tipo

TResult

Tipo del resultado que está disponible a través de Task<TResult>.The type of the result available through the Task<TResult>.

Parámetros

function
Func<Object,TResult>

Delegado de función que devuelve el resultado futuro que va a estar disponible a través de Task<TResult>.A function delegate that returns the future result to be available through the Task<TResult>.

state
Object Object Object Object

Objeto que contiene los datos que el delegado de function va a usar.An object containing data to be used by the function delegate.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar a la nueva tarea.The CancellationToken that will be assigned to the new task.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

Valor de TaskCreationOptions que controla el comportamiento del objeto Task<TResult> creado.A TaskCreationOptions value that controls the behavior of the created Task<TResult>.

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se usa para programar el objeto Task<TResult> creado.The TaskScheduler that is used to schedule the created Task<TResult>.

Devoluciones

Excepciones

La excepción que se produce cuando el argumento function es NULL.The exception that is thrown when the function argument is null.

O bien-or- La excepción que se produce cuando el argumento scheduler es NULL.The exception that is thrown when the scheduler argument is null.

La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. La excepción que se produce cuando el argumento creationOptions especifica un valor TaskCreationOptions no válido.The exception that is thrown when the creationOptions argument specifies an invalid TaskCreationOptions value. Para obtener más información, vea la sección Comentarios de FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions).For more information, see the Remarks for FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Comentarios

Llamar a StartNew equivale funcionalmente a la creación de un Task<TResult> utilizando uno de sus constructores y, a continuación, llamar a Start para programar su ejecución.Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

A partir de la .NET Framework 4.5.NET Framework 4.5, puede usar el Run método con un Action objeto como una forma rápida para llamar a StartNew con parámetros predeterminados.Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. Para obtener más información y ejemplos de código, vea la entrada Task.Run vs. Task.Factory.StartNew programación en paralelo con .NET blog.For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

Consulte también:

Se aplica a