TaskFactory.StartNew Método

Definição

Cria e inicia uma tarefa.

Sobrecargas

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

Cria e inicia uma tarefa para o delegado de ação, estado, token de cancelamento, opções de criação e agendador de tarefas especificados.

StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler)

Cria e inicia uma tarefa para o delegado de ação especificado, token de cancelamento, opções de criação e estado.

StartNew(Action<Object>, Object, TaskCreationOptions)

Cria e inicia uma tarefa para as opções de delegar de ação, estado e criação especificadas.

StartNew(Action<Object>, Object, CancellationToken)

Cria e inicia uma tarefa para o delegado, estado e token de cancelamento especificados.

StartNew(Action, CancellationToken)

Cria e inicia uma tarefa para o delegado de ação especificado e o token de cancelamento.

StartNew(Action, TaskCreationOptions)

Cria e inicia uma tarefa para as opções de delegação e criação de ação especificadas.

StartNew(Action)

Cria e inicia uma tarefa para o delegado de ação especificado.

StartNew(Action<Object>, Object)

Cria e inicia uma tarefa para a ação especificada, delegar e estabelecer.

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

Cria e inicia uma tarefa do tipo TResult para a função delegada, token de cancelamento, opções de criação e agendador de tarefas especificados.

StartNew<TResult>(Func<TResult>)

Cria e inicia uma tarefa do tipo TResult para a função delegada especificada.

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

Cria e inicia uma tarefa do tipo TResult para a função especificada delegar e estado.

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

Cria e inicia uma tarefa do tipo TResult para a função especificada de delegar e cancelamento.

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

Cria e inicia uma tarefa do tipo TResult para as funções especificadas de delegar e opções de criação.

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

Cria e inicia uma tarefa do tipo TResult para a função especificada: delegar, estar e token de cancelamento.

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

Cria e inicia uma tarefa do tipo TResult para as funções especificadas de delegar, estado e opções de criação.

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

Cria e inicia uma tarefa do tipo TResult para a função especificada: delegar, estado, token de cancelamento, opções de criação e agendador de tarefas.

Observações

A partir do .NET Framework 4.5, o método Task.Run é a forma recomendada de lançar uma tarefa ligada ao cálculo. Use o StartNew método apenas quando necessitar de controlo detalhado para uma tarefa de longa duração e limite de computação. Isto inclui cenários em que pretende controlar o seguinte:

  • Opções de criação de tarefas. As tarefas criadas pelo Task.Run método são criadas por defeito com a TaskCreationOptions.DenyChildAttach opção. Para sobrepor este comportamento, ou para oferecer outras TaskCreationOptions opções, chame uma StartNew sobrecarga.

  • Passagem de parâmetros. As sobrecargas do Task.Run método não permitem passar um parâmetro ao delegado da tarefa. As sobrecargas do StartNew método sim.

  • O agendador de tarefas. As sobrecargas do Task.Run método utilizam o agendador de tarefas por defeito. Para controlar o agendador de tarefas, chame uma StartNew sobrecarga com um scheduler parâmetro. Para obter mais informações, veja TaskScheduler.

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

Cria e inicia uma tarefa para o delegado de ação, estado, token de cancelamento, opções de criação e agendador de tarefas especificados.

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
Public Function StartNew (action As Action(Of Object), state As Object, cancellationToken As CancellationToken, creationOptions As TaskCreationOptions, scheduler As TaskScheduler) As Task

Parâmetros

action
Action<Object>

A ação delega para ser executada de forma assíncrona.

state
Object

Um objeto contendo dados a serem usados pelo action delegado.

cancellationToken
CancellationToken

O token de cancelamento que será atribuído à nova tarefa.

creationOptions
TaskCreationOptions

Um dos valores de enumeração que controla o comportamento da tarefa criada.

scheduler
TaskScheduler

O agendador de tarefas que é usado para agendar a tarefa criada.

Devoluções

A tarefa iniciada.

Exceções

O fornecido CancellationToken já foi descartado.

action é null.

-ou-

scheduler é null.

creationOptions argumento especifica um valor inválido TaskCreationOptions . Para mais informações, consulte as Observações para FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Observações

Chamar o StartNew é funcionalmente equivalente a criar uma Tarefa usando um dos seus construtores e depois chamá-la Start para agendar a execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, veja Task.Run vs Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler)

Cria e inicia uma tarefa para o delegado de ação especificado, token de cancelamento, opções de criação e estado.

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
Public Function StartNew (action As Action, cancellationToken As CancellationToken, creationOptions As TaskCreationOptions, scheduler As TaskScheduler) As Task

Parâmetros

action
Action

A ação delega para ser executada de forma assíncrona.

cancellationToken
CancellationToken

O token de cancelamento que será atribuído à nova tarefa.

creationOptions
TaskCreationOptions

Um dos valores de enumeração que controla o comportamento da tarefa criada.

scheduler
TaskScheduler

O agendador de tarefas que é usado para agendar a tarefa criada.

Devoluções

A tarefa iniciada.

Exceções

O fornecido CancellationToken já foi descartado.

action é null.

-ou-

scheduler é null.

creationOptions especifica um valor TaskCreationOptions inválido. Para mais informações, consulte as Observações para FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Observações

Chamar o StartNew é funcionalmente equivalente a criar uma Tarefa usando um dos seus construtores e depois chamá-la Start para agendar a execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, veja Task.Run vs Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

StartNew(Action<Object>, Object, TaskCreationOptions)

Cria e inicia uma tarefa para as opções de delegar de ação, estado e criação especificadas.

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>

A ação delega para ser executada de forma assíncrona.

state
Object

Um objeto contendo dados a serem usados pelo action delegado.

creationOptions
TaskCreationOptions

Um dos valores de enumeração que controla o comportamento da tarefa criada.

Devoluções

A tarefa iniciada.

Exceções

action é null.

creationOptions especifica um valor inválido TaskCreationOptions .

Observações

Chamar o StartNew é funcionalmente equivalente a criar uma Tarefa usando um dos seus construtores e depois chamá-la Start para agendar a execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, veja Task.Run vs Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

StartNew(Action<Object>, Object, CancellationToken)

Cria e inicia uma tarefa para o delegado, estado e token de cancelamento especificados.

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
Public Function StartNew (action As Action(Of Object), state As Object, cancellationToken As CancellationToken) As Task

Parâmetros

action
Action<Object>

A ação delega para ser executada de forma assíncrona.

state
Object

Um objeto contendo dados a serem usados pelo action delegado.

cancellationToken
CancellationToken

O token de cancelamento que será atribuído à nova tarefa.

Devoluções

A tarefa iniciada.

Exceções

O fornecido CancellationToken já foi descartado.

action é null.

Exemplos

O exemplo seguinte define um array de palavras de 6 letras. Cada palavra é então passada a um Action<T> delegado, que baralha a palavra e apresenta a palavra original e a sua versão embaralhada.

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

Note-se que o exemplo inicializa um único gerador de números aleatórios, que é protegido por um bloqueio. Para a necessidade de um cadeado, veja "O Sistema.Segurança aleatória de classes e fios" no Random tópico da aula. Para lidar com a possibilidade de corrupção do gerador de números aleatórios, um token de cancelamento é passado à tarefa. Se dois números aleatórios forem zero, o método assume que o gerador de números aleatórios está corrompido e define o token de cancelamento. Antes de ordenar o chars array que contém os seis caracteres de uma palavra, o método chama o CancellationToken.ThrowIfCancellationRequested método para lançar um OperationCanceledException se o token tiver sido cancelado.

Observações

Chamar o StartNew é funcionalmente equivalente a criar uma Tarefa usando um dos seus construtores e depois chamá-la Start para agendar a execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, veja Task.Run vs Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

StartNew(Action, CancellationToken)

Cria e inicia uma tarefa para o delegado de ação especificado e o token de cancelamento.

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
Public Function StartNew (action As Action, cancellationToken As CancellationToken) As Task

Parâmetros

action
Action

A ação delega para ser executada de forma assíncrona.

cancellationToken
CancellationToken

O token de cancelamento que será atribuído à nova tarefa.

Devoluções

A tarefa iniciada.

Exceções

O fornecido CancellationToken já foi descartado.

action é null.

Exemplos

O exemplo seguinte chama o método StartNew(Action, CancellationToken) para criar uma tarefa que itera os ficheiros no diretório C:\Windows\System32. A expressão lambda chama o Parallel.ForEach método para adicionar informação sobre cada ficheiro a um List<T> objeto. Cada tarefa aninhada destacada invocada pelo Parallel.ForEach loop verifica o estado do token de cancelamento e, se for solicitado cancelamento, chama o CancellationToken.ThrowIfCancellationRequested método. O CancellationToken.ThrowIfCancellationRequested método lança uma OperationCanceledException exceção que é tratada num catch bloco quando o thread que chama o Task.Wait método.

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

Observações

Chamar StartNew é funcionalmente equivalente a criar uma Tarefa usando um dos seus construtores e depois chamar Start para a agendar para execução.

A partir do .NET Framework 4.5, podes usar o método Task.Run(Action, CancellationToken) como uma forma rápida de chamar StartNew(Action, CancellationToken) com parâmetros padrão. Note-se, no entanto, que existe uma diferença de comportamento entre os dois métodos relativamente a : Task.Run(Action, CancellationToken) por defeito, não permite tarefas filhos iniciadas com a TaskCreationOptions.AttachedToParent opção de anexar à instância atual Task , enquanto StartNew(Action, CancellationToken) permite. Para mais informações e exemplos de código, veja Task.Run vs Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

StartNew(Action, TaskCreationOptions)

Cria e inicia uma tarefa para as opções de delegação e criação de ação especificadas.

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
Public Function StartNew (action As Action, creationOptions As TaskCreationOptions) As Task

Parâmetros

action
Action

A ação delega para ser executada de forma assíncrona.

creationOptions
TaskCreationOptions

Um dos valores de enumeração que controla o comportamento da tarefa criada.

Devoluções

A tarefa iniciada.

Exceções

action é null.

creationOptions especifica um valor inválido TaskCreationOptions .

Observações

Chamar o StartNew é funcionalmente equivalente a criar uma Tarefa usando um dos seus construtores e depois chamá-la Start para agendar a execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, veja Task.Run vs Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

StartNew(Action)

Cria e inicia uma tarefa para o delegado de ação especificado.

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

Parâmetros

action
Action

A ação delega para ser executada de forma assíncrona.

Devoluções

A tarefa iniciada.

Exceções

O action argumento é null.

Exemplos

O exemplo seguinte utiliza o StartNew(Action) método para invocar repetidamente um Action delegado que gera um número aleatório, interpreta-o como um ponto de código Unicode, converte-o numa unidade de código codificada em UTF16 e apresenta informação sobre o carácter ou caracteres resultantes.

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 += $"0x{(ushort)ch:X} ";
      }   
      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)

Observações

Chamar StartNew é funcionalmente equivalente a criar uma tarefa usando um dos seus construtores e depois chamar o Task.Start método para agendar a tarefa para execução.

A partir do .NET Framework 4.5, podes usar o método Task.Run(Action) como uma forma rápida de chamar StartNew(Action) com parâmetros padrão. Note-se, no entanto, que existe uma diferença de comportamento entre os dois métodos relativamente a : Task.Run(Action) por defeito, não permite tarefas filhos iniciadas com a TaskCreationOptions.AttachedToParent opção de anexar à instância atual Task , enquanto StartNew(Action) permite. Para mais informações e exemplos de código, veja Task.Run vs Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

StartNew(Action<Object>, Object)

Cria e inicia uma tarefa para a ação especificada, delegar e estabelecer.

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>

A ação delega para ser executada de forma assíncrona.

state
Object

Um objeto contendo dados a serem usados pelo action delegado.

Devoluções

A tarefa iniciada.

Exceções

O action argumento é null.

Exemplos

O exemplo seguinte define um array de palavras de 6 letras. Cada palavra é então passada a um Action<T> delegado, que baralha a palavra e apresenta a palavra original e a sua versão embaralhada.

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

Note-se que o exemplo inicializa um único gerador de números aleatórios, que é protegido por um bloqueio. Para a necessidade de um cadeado, veja "O Sistema.Segurança aleatória de classes e fios" no Random tópico da aula.

Observações

Chamar StartNew é funcionalmente equivalente a criar um Task usando um dos seus construtores e depois chamar o Start método para o agendar para execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, veja Task.Run vs Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

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

Cria e inicia uma tarefa do tipo TResult para a função delegada, token de cancelamento, opções de criação e agendador de tarefas especificados.

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>
Public Function StartNew(Of TResult) (function As Func(Of TResult), cancellationToken As CancellationToken, creationOptions As TaskCreationOptions, scheduler As TaskScheduler) As Task(Of TResult)

Parâmetros de Tipo Genérico

TResult

O tipo de resultado disponível através da tarefa.

Parâmetros

function
Func<TResult>

Um delegado de função que devolve o resultado futuro para estar disponível através da tarefa.

cancellationToken
CancellationToken

O token de cancelamento que será atribuído à nova tarefa.

creationOptions
TaskCreationOptions

Um dos valores de enumeração que controla o comportamento da tarefa criada.

scheduler
TaskScheduler

O agendador de tarefas que é usado para agendar a tarefa criada.

Devoluções

A tarefa iniciada.

Exceções

O fornecido CancellationToken já foi descartado.

function é null.

-ou-

scheduler é null.

creationOptions especifica um valor inválido TaskCreationOptions . Para mais informações, consulte as Observações para FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Observações

Chamar StartNew é funcionalmente equivalente a criar um Task<TResult> usando um dos seus construtores e depois chamar Start para o agendar para execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, consulte a entrada Task.Run vs. Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

StartNew<TResult>(Func<TResult>)

Cria e inicia uma tarefa do tipo TResult para a função delegada especificada.

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 Genérico

TResult

O tipo de resultado disponível através da tarefa.

Parâmetros

function
Func<TResult>

Um delegado de função que devolve o resultado futuro para estar disponível através da tarefa.

Devoluções

A tarefa iniciada.

Exceções

O function argumento é null.

Exemplos

O exemplo seguinte é uma aplicação simples de soma que gera dois números aleatórios e pede ao utilizador para introduzir a sua soma. Indica então se a resposta está correta ou, se a resposta do utilizador não for um número válido, convida o utilizador a introduzir novamente um número válido. O StartNew é usado para criar os Task<TResult> objetos que retornam os números aleatórios para somar.

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

Observações

Chamar StartNew é funcionalmente equivalente a criar um Task<TResult> usando um dos seus construtores e depois chamar Start para o agendar para execução.

A partir do .NET Framework 4.5, pode chamar o método Task.Run<TResult>(Func<TResult>) como forma rápida de chamar StartNew com parâmetros padrão. Note-se, no entanto, que existe uma diferença de comportamento entre os dois métodos relativamente a : Task.Run<TResult>(Func<TResult>) por defeito, não permite tarefas filhos iniciadas com a TaskCreationOptions.AttachedToParent opção de anexar à instância atual Task<TResult> , enquanto StartNew<TResult>(Func<TResult>) permite. Para mais informações e exemplos de código, consulte a entrada Task.Run vs. Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

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

Cria e inicia uma tarefa do tipo TResult para a função especificada delegar e estado.

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 Genérico

TResult

O tipo de resultado disponível através da tarefa.

Parâmetros

function
Func<Object,TResult>

Um delegado de função que devolve o resultado futuro para estar disponível através da tarefa.

state
Object

Um objeto contendo dados a serem usados pelo function delegado.

Devoluções

A tarefa iniciada.

Exceções

function é null.

Observações

Chamar StartNew é funcionalmente equivalente a criar um Task<TResult> usando um dos seus construtores e depois chamar Start para o agendar para execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, consulte a entrada Task.Run vs. Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

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

Cria e inicia uma tarefa do tipo TResult para a função especificada de delegar e cancelamento.

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>
Public Function StartNew(Of TResult) (function As Func(Of TResult), cancellationToken As CancellationToken) As Task(Of TResult)

Parâmetros de Tipo Genérico

TResult

O tipo de resultado disponível através da tarefa.

Parâmetros

function
Func<TResult>

Um delegado de função que devolve o resultado futuro para estar disponível através da tarefa.

cancellationToken
CancellationToken

O token de cancelamento que será atribuído à nova tarefa.

Devoluções

A tarefa iniciada.

Exceções

O fornecido CancellationToken já foi descartado.

function é null.

Exemplos

O exemplo seguinte utiliza duas tarefas para calcular a sequência de Fibonacci que termina em F100 = F100-1 + F100-2 com valores semente F1= 1, F2 = 1 e F1 = 0, F2= 1. Aproximadamente metade das vezes, um token de cancelamento é definido à medida que as operações são executadas. A saída do exemplo mostra o resultado se as duas tarefas forem concluídas com sucesso e se o token for cancelado.

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.

Observações

Chamar StartNew é funcionalmente equivalente a criar um Task<TResult> usando um dos seus construtores e depois chamar Start para o agendar para execução.

A partir do .NET Framework 4.5, podes usar o método Task.Run<TResult>(Func<TResult>, CancellationToken) como uma forma rápida de chamar StartNew<TResult>(Func<TResult>, CancellationToken) com parâmetros padrão. Note-se, no entanto, que existe uma diferença de comportamento entre os dois métodos relativamente a : Task.Run<TResult>(Func<TResult>, CancellationToken) por defeito, não permite tarefas filhos iniciadas com a TaskCreationOptions.AttachedToParent opção de anexar à instância atual Task<TResult> , enquanto StartNew<TResult>(Func<TResult>, CancellationToken) permite. Para mais informações e exemplos de código, consulte a entrada Task.Run vs. Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

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

Cria e inicia uma tarefa do tipo TResult para as funções especificadas de delegar e opções de criação.

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 Genérico

TResult

O tipo de resultado disponível através da tarefa.

Parâmetros

function
Func<TResult>

Um delegado de função que devolve o resultado futuro para estar disponível através da tarefa.

creationOptions
TaskCreationOptions

Um dos valores de enumeração que controla o comportamento da tarefa criada.

Devoluções

A tarefa iniciada.

Exceções

function é null.

creationOptions especifica um valor inválido TaskCreationOptions . Para mais informações, consulte as Observações para FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Observações

Chamar StartNew é funcionalmente equivalente a criar um Task<TResult> usando um dos seus construtores e depois chamar Start para o agendar para execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, consulte a entrada Task.Run vs. Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

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

Cria e inicia uma tarefa do tipo TResult para a função especificada: delegar, estar e token de cancelamento.

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>
Public Function StartNew(Of TResult) (function As Func(Of Object, TResult), state As Object, cancellationToken As CancellationToken) As Task(Of TResult)

Parâmetros de Tipo Genérico

TResult

O tipo de resultado disponível através da tarefa.

Parâmetros

function
Func<Object,TResult>

Um delegado de função que devolve o resultado futuro para estar disponível através da tarefa.

state
Object

Um objeto contendo dados a serem usados pelo function delegado.

cancellationToken
CancellationToken

O token de cancelamento que será atribuído à nova tarefa.

Devoluções

A tarefa iniciada.

Exceções

O fornecido CancellationToken já foi descartado.

function é null.

Observações

Chamar StartNew é funcionalmente equivalente a criar um Task<TResult> usando um dos seus construtores e depois chamar Start para o agendar para execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, consulte a entrada Task.Run vs. Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

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

Cria e inicia uma tarefa do tipo TResult para as funções especificadas de delegar, estado e opções de criação.

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 Genérico

TResult

O tipo de resultado disponível através da tarefa.

Parâmetros

function
Func<Object,TResult>

Um delegado de função que devolve o resultado futuro para estar disponível através da tarefa.

state
Object

Um objeto contendo dados a serem usados pelo function delegado.

creationOptions
TaskCreationOptions

Um dos valores de enumeração que controla o comportamento da tarefa criada.

Devoluções

A tarefa iniciada.

Exceções

function é null.

creationOptions especifica um valor inválido TaskCreationOptions . Para mais informações, consulte as Observações para FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Observações

Chamar StartNew é funcionalmente equivalente a criar um Task<TResult> usando um dos seus construtores e depois chamar Start para o agendar para execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, consulte a entrada Task.Run vs. Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a

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

Cria e inicia uma tarefa do tipo TResult para a função especificada: delegar, estado, token de cancelamento, opções de criação e agendador de tarefas.

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>
Public Function StartNew(Of TResult) (function As Func(Of Object, TResult), state As Object, cancellationToken As CancellationToken, creationOptions As TaskCreationOptions, scheduler As TaskScheduler) As Task(Of TResult)

Parâmetros de Tipo Genérico

TResult

O tipo de resultado disponível através da tarefa.

Parâmetros

function
Func<Object,TResult>

Um delegado de função que devolve o resultado futuro para estar disponível através da tarefa.

state
Object

Um objeto contendo dados a serem usados pelo function delegado.

cancellationToken
CancellationToken

O token de cancelamento que será atribuído à nova tarefa.

creationOptions
TaskCreationOptions

Um dos valores de enumeração que controla o comportamento da tarefa criada.

scheduler
TaskScheduler

O agendador de tarefas que é usado para agendar a tarefa criada.

Devoluções

A tarefa iniciada.

Exceções

O fornecido CancellationToken já foi descartado.

function é null.

-ou-

scheduler é null.

creationOptions especifica um valor inválido TaskCreationOptions . Para mais informações, consulte as Observações para FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Observações

Chamar StartNew é funcionalmente equivalente a criar um Task<TResult> usando um dos seus construtores e depois chamar Start para o agendar para execução.

Começando pelo .NET Framework 4.5, podes usar o método Run com um objeto Action como forma rápida de chamar StartNew com parâmetros padrão. Para mais informações e exemplos de código, consulte a entrada Task.Run vs. Task.Factory.StartNew no blogue Parallel Programming with .NET.

Ver também

Aplica-se a