Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Método TaskFactory.StartNew (Action<Object>, Object, CancellationToken)

.NET Framework (current version)
 

Cria e inicia um Task.

Namespace:   System.Threading.Tasks
Assembly:  mscorlib (em mscorlib.dll)

public Task StartNew(
	Action<object> action,
	object state,
	CancellationToken cancellationToken
)

Parâmetros

action
Type: System.Action<Object>

O delegado da ação a ser executado de forma assíncrona.

state
Type: System.Object

Um objeto que contém dados a serem usados pelo delegado action.

cancellationToken
Type: System.Threading.CancellationToken

O CancellationToken que será atribuído ao novo Task

Valor Retornado

Type: System.Threading.Tasks.Task

O Task iniciado.

Exception Condition
ObjectDisposedException

O CancellationToken fornecido já foi descartado.

ArgumentNullException

A exceção lançada quando o argumento action é nulo.

Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling M:System.Threading.Tasks.Task.Start to schedule it for execution.

Starting with the net_v45, you can use the Overload:System.Threading.Tasks.Task.Run method with an T:System.Action object as a quick way to call Overload:System.Threading.Tasks.TaskFactory.StartNew with default parameters. For more information and code examples, see Task.Run vs Task.Factory.StartNewhttp://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx in the Parallel Programming with .NET blog.

The following example defines an array of 6-letter words. Each word is then passed to an T:System.Action`1 delegate, which scrambles the word and displays the original word and its scrambled version.

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

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

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

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

Note that the example initializes a single random number generator, which is protected by a lock. For the need of a lock, see "The System.Random class and thread safety" in the T:System.Random class topic. To handle the possibility of corruption of the random number generator, a cancellation token is passed to task. If two random numbers equal zero, the method assumes that the random number generator is corrupted and sets the cancellation token. Before sorting the chars array that contains the six characters in a word, the method calls the M:System.Threading.CancellationToken.ThrowIfCancellationRequested method to throw an T:System.OperationCanceledException if the token has been canceled.

Plataforma Universal do Windows
Disponível desde 8
.NET Framework
Disponível desde 4.0
Biblioteca de Classes Portátil
Com suporte no: plataformas portáteis do .NET
Silverlight
Disponível desde 5.0
Windows Phone Silverlight
Disponível desde 8.0
Windows Phone
Disponível desde 8.1
Retornar ao início
Mostrar: