Task Task Task Task Constructors

Definición

Sobrecargas

Task(Action) Task(Action) Task(Action)

Inicializa una nueva instancia de Task con la acción especificada.Initializes a new Task with the specified action.

Task(Action, CancellationToken) Task(Action, CancellationToken) Task(Action, CancellationToken)

Inicializa una nueva instancia de Task con la acción y CancellationToken especificados.Initializes a new Task with the specified action and CancellationToken.

Task(Action, TaskCreationOptions) Task(Action, TaskCreationOptions) Task(Action, TaskCreationOptions)

Inicializa un nuevo objeto Task con la acción y las opciones de creación especificadas.Initializes a new Task with the specified action and creation options.

Task(Action<Object>, Object) Task(Action<Object>, Object) Task(Action<Object>, Object) Task(Action<Object>, Object)

Inicializa un nuevo objeto Task con la acción y el estado especificados.Initializes a new Task with the specified action and state.

Task(Action, CancellationToken, TaskCreationOptions) Task(Action, CancellationToken, TaskCreationOptions) Task(Action, CancellationToken, TaskCreationOptions)

Inicializa un nuevo objeto Task con la acción y las opciones de creación especificadas.Initializes a new Task with the specified action and creation options.

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

Inicializa un nuevo objeto Task con la acción, el estado y las opciones especificados.Initializes a new Task with the specified action, state, and options.

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

Inicializa un nuevo objeto Task con la acción, el estado y las opciones especificados.Initializes a new Task with the specified action, state, and options.

Task(Action<Object>, Object, CancellationToken, TaskCreationOptions) Task(Action<Object>, Object, CancellationToken, TaskCreationOptions) Task(Action<Object>, Object, CancellationToken, TaskCreationOptions)

Inicializa un nuevo objeto Task con la acción, el estado y las opciones especificados.Initializes a new Task with the specified action, state, and options.

Task(Action) Task(Action) Task(Action)

Inicializa una nueva instancia de Task con la acción especificada.Initializes a new Task with the specified action.

public:
 Task(Action ^ action);
public Task (Action action);
new System.Threading.Tasks.Task : Action -> System.Threading.Tasks.Task

Parámetros

action
Action Action Action Action

El delegado que representa el código que se va a ejecutar en la tarea.The delegate that represents the code to execute in the task.

Excepciones

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

Ejemplos

En el ejemplo siguiente se Task(Action) utiliza el constructor para crear tareas que recuperan los nombres de archivo en los directorios especificados.The following example uses the Task(Action) constructor to create tasks that retrieve the filenames in specified directories. Todas las tareas escriben los nombres de archivo ConcurrentBag<T> en un solo objeto.All tasks write the file names to a single ConcurrentBag<T> object. A continuación, el ejemplo WaitAll(Task[]) llama al método para asegurarse de que todas las tareas se han completado y, a continuación, muestra un recuento del número ConcurrentBag<T> total de nombres de archivo escritos en el objeto.The example then calls the WaitAll(Task[]) method to ensure that all tasks have completed, and then displays a count of the total number of file names written to the ConcurrentBag<T> object.

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

public class Example
{
   public static async Task Main()
   {
      var list = new ConcurrentBag<string>();
      string[] dirNames = { ".", ".." };
      List<Task> tasks = new List<Task>();
      foreach (var dirName in dirNames) {
         Task t = new Task( () => { foreach(var path in Directory.GetFiles(dirName))
                                    list.Add(path); }  );
         tasks.Add(t);
         t.Start();
      }
      await Task.WhenAll(tasks.ToArray());
      foreach (Task t in tasks)
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status);
         
      Console.WriteLine("Number of files read: {0}", list.Count);
   }
}
// The example displays output like the following:
//       Task 1 Status: RanToCompletion
//       Task 2 Status: RanToCompletion
//       Number of files read: 23
Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim list As New ConcurrentBag(Of String)()
      Dim dirNames() As String = { ".", ".." }
      Dim tasks As New List(Of Task)()
      For Each dirName In dirNames 
         Dim t As New Task( Sub()
                               For Each path In Directory.GetFiles(dirName)
                                  list.Add(path)
                               Next
                            End Sub  )
         tasks.Add(t)
         t.Start()
      Next
      Task.WaitAll(tasks.ToArray())
      For Each t In tasks
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status)
      Next   
      Console.WriteLine("Number of files read: {0}", list.Count)
   End Sub
End Module
' The example displays output like the following:
'       Task 1 Status: RanToCompletion
'       Task 2 Status: RanToCompletion
'       Number of files read: 23

El ejemplo siguiente es idéntico, salvo que se utilizó el Run(Action) método para crear una instancia de la tarea en una sola operación.The following example is identical, except that it used the Run(Action) method to instantiate and run the task in a single operation. El método devuelve el Task objeto que representa la tarea.The method returns the Task object that represents the task.

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

public class Example
{
   public static void Main()
   {
      var list = new ConcurrentBag<string>();
      string[] dirNames = { ".", ".." };
      List<Task> tasks = new List<Task>();
      foreach (var dirName in dirNames) {
         Task t = Task.Run( () => { foreach(var path in Directory.GetFiles(dirName)) 
                                       list.Add(path); }  );
         tasks.Add(t);
      }
      Task.WaitAll(tasks.ToArray());
      foreach (Task t in tasks)
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status);
         
      Console.WriteLine("Number of files read: {0}", list.Count);
   }
}
// The example displays output like the following:
//       Task 1 Status: RanToCompletion
//       Task 2 Status: RanToCompletion
//       Number of files read: 23
Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim list As New ConcurrentBag(Of String)()
      Dim dirNames() As String = { ".", ".." }
      Dim tasks As New List(Of Task)()
      For Each dirName In dirNames 
         Dim t As Task = Task.Run( Sub()
                                      For Each path In Directory.GetFiles(dirName) 
                                         list.Add(path)
                                      Next
                                   End Sub  )
         tasks.Add(t)
      Next
      Task.WaitAll(tasks.ToArray())
      For Each t In tasks
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status)
      Next   
      Console.WriteLine("Number of files read: {0}", list.Count)
   End Sub
End Module
' The example displays output like the following:
'       Task 1 Status: RanToCompletion
'       Task 2 Status: RanToCompletion
'       Number of files read: 23

Comentarios

Este constructor solo debe usarse en escenarios avanzados en los que es necesario que la creación y el inicio de la tarea se separan.This constructor should only be used in advanced scenarios where it is required that the creation and starting of the task is separated.

En lugar de llamar a este constructor, la manera más común de crear Task una instancia de un objeto e iniciar una tarea es Task.Run(Action) llamando TaskFactory.StartNew(Action) al método estático o.Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static Task.Run(Action) or TaskFactory.StartNew(Action) method.

Si una tarea sin ninguna acción es necesaria solo para que el consumidor de una API tenga algo que esperar, TaskCompletionSource<TResult> se debe usar.If a task with no action is needed just for the consumer of an API to have something to await, a TaskCompletionSource<TResult> should be used.

Consulte también:

Task(Action, CancellationToken) Task(Action, CancellationToken) Task(Action, CancellationToken)

Inicializa una nueva instancia de Task con la acción y CancellationToken especificados.Initializes a new Task with the specified action and CancellationToken.

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

Parámetros

action
Action Action Action Action

El delegado que representa el código que se va a ejecutar en la tarea.The delegate that represents the code to execute in the task.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

El CancellationToken que observará la nueva tarea.The CancellationToken that the new task will observe.

Excepciones

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

Ejemplos

En el ejemplo siguiente se Task(Action, CancellationToken) llama al constructor para crear una tarea que recorra en iteración los archivos del directorio C:\windows\system32.The following example calls the Task(Action, CancellationToken) constructor to create a task that iterates the files in the C:\Windows\System32 directory. La expresión lambda llama Parallel.ForEach al método para agregar información sobre 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 tarea anidada desasociada invocada por el Parallel.ForEach bucle comprueba el estado del token de cancelación y, si se solicita la cancelación, llama CancellationToken.ThrowIfCancellationRequested al 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 bloque cuando el subproceso que realiza la Task.Wait llamada llama al 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. A continuación, se llama al métodoparainiciarlatarea.StartThe Start method is then called to start the task.

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

public class Example
{
   public static async Task Main()
   {
      var tokenSource = new CancellationTokenSource();
      var token = tokenSource.Token;
      var files = new List<Tuple<string, string, long, DateTime>>();
      
      var t = new Task(() => { 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);
      t.Start();
      tokenSource.Cancel();
      try {
         await t; 
         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 New Task(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)
      t.Start()
      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

En lugar de llamar a este constructor, la manera más común de crear Task una instancia de un objeto e iniciar una tarea es Task.Run(Action, CancellationToken) mediante TaskFactory.StartNew(Action, CancellationToken) una llamada a los métodos estáticos y.Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static Task.Run(Action, CancellationToken) and TaskFactory.StartNew(Action, CancellationToken) methods. La única ventaja que ofrece este constructor es que permite que la creación de instancias de objeto se separe de la invocación de la tarea.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

Para obtener más información, consulte paralelismo de tareas (Task Parallel Library) y cancelación ensubprocesos administrados.For more information, see Task Parallelism (Task Parallel Library) and Cancellation in Managed Threads.

Task(Action, TaskCreationOptions) Task(Action, TaskCreationOptions) Task(Action, TaskCreationOptions)

Inicializa un nuevo objeto Task con la acción y las opciones de creación especificadas.Initializes a new Task with the specified action and creation options.

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

Parámetros

action
Action Action Action Action

El delegado que representa el código que se va a ejecutar en la tarea.The delegate that represents the code to execute in the task.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

El objeto TaskCreationOptions que se usa para personalizar el comportamiento de la tarea.The TaskCreationOptions used to customize the task's behavior.

Excepciones

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

El argumento creationOptions especifica un valor no válido para TaskCreationOptions.The creationOptions argument specifies an invalid value for TaskCreationOptions.

Comentarios

En lugar de llamar a este constructor, la manera más común de crear Task una instancia de un objeto e iniciar una tarea es TaskFactory.StartNew(Action, TaskCreationOptions) llamando al método estático.Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action, TaskCreationOptions) method. La única ventaja que ofrece este constructor es que permite que la creación de instancias de objeto se separe de la invocación de la tarea.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

Task(Action<Object>, Object) Task(Action<Object>, Object) Task(Action<Object>, Object) Task(Action<Object>, Object)

Inicializa un nuevo objeto Task con la acción y el estado especificados.Initializes a new Task with the specified action and state.

public:
 Task(Action<System::Object ^> ^ action, System::Object ^ state);
public Task (Action<object> action, object state);
new System.Threading.Tasks.Task : Action<obj> * obj -> System.Threading.Tasks.Task
Public Sub New (action As Action(Of Object), state As Object)

Parámetros

action
Action<Object>

El delegado que representa el código que se va a ejecutar en la tarea.The delegate that represents the code to execute in the task.

state
Object Object Object Object

Objeto que representa los datos que la acción va a usar.An object representing data to be used by the action.

Excepciones

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

Ejemplos

En el ejemplo siguiente se define una matriz de palabras de seis letras.The following example defines an array of 6-letter words. Después, cada palabra se pasa como un argumento al Task(Action<Object>, Object) constructor, cuyo Action<T> delegado codifica los caracteres de la palabra y, a continuación, muestra la palabra original y su versión codificada.Each word is then passed as an argument to the Task(Action<Object>, Object) constructor, whose Action<T> delegate scrambles the characters in the word, then displays the original word and its scrambled version.

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

public class Example
{
   public static async Task 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) {
         Task t = new Task( (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);
         t.Start();
         tasks.Add(t);
      }
      await Task.WhenAll(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
         Dim t As New Task( 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)
         t.Start()
         tasks.Add(t)
      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

Comentarios

En lugar de llamar a este constructor, la manera más común de crear Task una instancia de un objeto e iniciar una tarea es TaskFactory.StartNew(Action<Object>, Object) llamando al método estático.Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action<Object>, Object) method. La única ventaja que ofrece este constructor es que permite que la creación de instancias de objeto se separe de la invocación de la tarea.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

Consulte también:

Task(Action, CancellationToken, TaskCreationOptions) Task(Action, CancellationToken, TaskCreationOptions) Task(Action, CancellationToken, TaskCreationOptions)

Inicializa un nuevo objeto Task con la acción y las opciones de creación especificadas.Initializes a new Task with the specified action and creation options.

public:
 Task(Action ^ action, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Action action, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task : Action * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task

Parámetros

action
Action Action Action Action

El delegado que representa el código que se va a ejecutar en la tarea.The delegate that represents the code to execute in the task.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que la nueva tarea observará.The CancellationToken that the new task will observe.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

El objeto TaskCreationOptions que se usa para personalizar el comportamiento de la tarea.The TaskCreationOptions used to customize the task's behavior.

Excepciones

El CancellationTokenSource que creó cancellationToken ya se ha eliminado.The CancellationTokenSource that created cancellationToken has already been disposed.

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

El argumento creationOptions especifica un valor no válido para TaskCreationOptions.The creationOptions argument specifies an invalid value for TaskCreationOptions.

Comentarios

En lugar de llamar a este constructor, la manera más común de crear Task una instancia de un objeto e iniciar una tarea es TaskFactory.StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler) llamando al método estático.Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler) method. La única ventaja que ofrece este constructor es que permite que la creación de instancias de objeto se separe de la invocación de la tarea.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

Para obtener más información, consulte paralelismo de tareas (Task Parallel Library) y cancelación de tareas.For more information, see Task Parallelism (Task Parallel Library) and Task Cancellation.

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

Inicializa un nuevo objeto Task con la acción, el estado y las opciones especificados.Initializes a new Task with the specified action, state, and options.

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

Parámetros

action
Action<Object>

El delegado que representa el código que se va a ejecutar en la tarea.The delegate that represents the code to execute in the task.

state
Object Object Object Object

Objeto que representa los datos que la acción va a usar.An object representing data to be used by the action.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que la nueva tarea observará.The CancellationToken that the new task will observe.

Excepciones

El CancellationTokenSource que creó cancellationToken ya se ha eliminado.The CancellationTokenSource that created cancellationToken has already been disposed.

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

Comentarios

En lugar de llamar a este constructor, la manera más común de crear Task una instancia de un objeto e iniciar una tarea es TaskFactory.StartNew(Action<Object>, Object, CancellationToken) llamando al método estático.Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action<Object>, Object, CancellationToken) method. La única ventaja que ofrece este constructor es que permite que la creación de instancias de objeto se separe de la invocación de la tarea.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

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

Inicializa un nuevo objeto Task con la acción, el estado y las opciones especificados.Initializes a new Task with the specified action, state, and options.

public:
 Task(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Action<object> action, object state, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task : Action<obj> * obj * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task
Public Sub New (action As Action(Of Object), state As Object, creationOptions As TaskCreationOptions)

Parámetros

action
Action<Object>

El delegado que representa el código que se va a ejecutar en la tarea.The delegate that represents the code to execute in the task.

state
Object Object Object Object

Objeto que representa los datos que la acción va a usar.An object representing data to be used by the action.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

El objeto TaskCreationOptions que se usa para personalizar el comportamiento de la tarea.The TaskCreationOptions used to customize the task's behavior.

Excepciones

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

El argumento creationOptions especifica un valor no válido para TaskCreationOptions.The creationOptions argument specifies an invalid value for TaskCreationOptions.

Comentarios

En lugar de llamar a este constructor, la manera más común de crear Task una instancia de un objeto e iniciar una tarea es TaskFactory.StartNew(Action<Object>, Object, TaskCreationOptions) llamando al método estático.Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action<Object>, Object, TaskCreationOptions) method. La única ventaja que ofrece este constructor es que permite que la creación de instancias de objeto se separe de la invocación de la tarea.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

Task(Action<Object>, Object, CancellationToken, TaskCreationOptions) Task(Action<Object>, Object, CancellationToken, TaskCreationOptions) Task(Action<Object>, Object, CancellationToken, TaskCreationOptions)

Inicializa un nuevo objeto Task con la acción, el estado y las opciones especificados.Initializes a new Task with the specified action, state, and options.

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

Parámetros

action
Action<Object>

El delegado que representa el código que se va a ejecutar en la tarea.The delegate that represents the code to execute in the task.

state
Object Object Object Object

Objeto que representa los datos que la acción va a usar.An object representing data to be used by the action.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que la nueva tarea observará.The CancellationToken that the new task will observe.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions TaskCreationOptions

El objeto TaskCreationOptions que se usa para personalizar el comportamiento de la tarea.The TaskCreationOptions used to customize the task's behavior.

Excepciones

El CancellationTokenSource que creó cancellationToken ya se ha eliminado.The CancellationTokenSource that created cancellationToken has already been disposed.

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

El argumento creationOptions especifica un valor no válido para TaskCreationOptions.The creationOptions argument specifies an invalid value for TaskCreationOptions.

Comentarios

En lugar de llamar a este constructor, la manera más común de crear Task una instancia de un objeto e iniciar una tarea es TaskFactory.StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) llamando al método estático.Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) method. La única ventaja que ofrece este constructor es que permite que la creación de instancias de objeto se separe de la invocación de la tarea.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

Se aplica a