Task.RunSynchronously Método

Definição

Executa o Task de forma síncrona no TaskScheduler atual.Runs the Task synchronously on the current TaskScheduler.

Sobrecargas

RunSynchronously()

Executa o Task de forma síncrona no TaskScheduler atual.Runs the Task synchronously on the current TaskScheduler.

RunSynchronously(TaskScheduler)

Executa o Task de forma síncrona no TaskScheduler fornecido.Runs the Task synchronously on the TaskScheduler provided.

RunSynchronously()

Executa o Task de forma síncrona no TaskScheduler atual.Runs the Task synchronously on the current TaskScheduler.

public:
 void RunSynchronously();
public void RunSynchronously ();
member this.RunSynchronously : unit -> unit
Public Sub RunSynchronously ()

Exceções

A instância Task foi descartada.The Task instance has been disposed.

O Task não está em um estado válido para ser iniciado.The Task is not in a valid state to be started. Ele pode já ter sido iniciado, executado ou cancelado ou pode ter sido criado de forma a não dar suporte ao agendamento direto.It may have already been started, executed, or canceled, or it may have been created in a manner that doesn't support direct scheduling.

Exemplos

O exemplo a seguir compara uma tarefa executada chamando o método RunSynchronously com um executado de forma assíncrona.The following example compares a task executed by calling the RunSynchronously method with one executed asynchronously. Em ambos os casos, as tarefas executam expressões lambda idênticas que exibem a ID da tarefa e a ID do thread no qual a tarefa está em execução.In both cases, the tasks execute identical lambda expressions that display the task ID and the ID of the thread on which the task is running. A tarefa calcula a soma dos inteiros entre 1 e 1 milhão.The task calculates the sum of the integers between 1 and 1,000,000. Como a saída do exemplo mostra, a tarefa executada chamando o método RunSynchronously é executada no thread do aplicativo, enquanto a tarefa assíncrona não faz isso.As the output from the example shows, the task executed by calling the RunSynchronously method runs on the application thread, while the asynchronous task does not.

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

public class Example
{
   public static void Main()
   {
      Console.WriteLine("Application executing on thread {0}",
                        Thread.CurrentThread.ManagedThreadId);
      var asyncTask = Task.Run( () => {  Console.WriteLine("Task {0} (asyncTask) executing on Thread {1}",
                                                           Task.CurrentId,
                                                           Thread.CurrentThread.ManagedThreadId);
                                         long sum = 0;
                                         for (int ctr = 1; ctr <= 1000000; ctr++ )
                                            sum += ctr;
                                         return sum;
                                      });
      var syncTask = new Task<long>( () =>  { Console.WriteLine("Task {0} (syncTask) executing on Thread {1}",
                                                                 Task.CurrentId,
                                                                 Thread.CurrentThread.ManagedThreadId);
                                              long sum = 0;
                                              for (int ctr = 1; ctr <= 1000000; ctr++ )
                                                 sum += ctr;
                                              return sum;
                                            });
      syncTask.RunSynchronously();
      Console.WriteLine();
      Console.WriteLine("Task {0} returned {1:N0}", syncTask.Id, syncTask.Result);
      Console.WriteLine("Task {0} returned {1:N0}", asyncTask.Id, asyncTask.Result);
   }
}
// The example displays the following output:
//       Application executing on thread 1
//       Task 1 (syncTask) executing on Thread 1
//       Task 2 (asyncTask) executing on Thread 3
//       1 status: RanToCompletion
//       2 status: RanToCompletion
//
//       Task 2 returned 500,000,500,000
//       Task 1 returned 500,000,500,000
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Console.WriteLine("Application executing on thread {0}",
                        Thread.CurrentThread.ManagedThreadId)
      Dim asyncTask = Task.Run( Function()
                                   Console.WriteLine("Task {0} (asyncTask) executing on Thread {1}",
                                                     Task.CurrentId,
                                                     Thread.CurrentThread.ManagedThreadId)
                                   Dim sum As Long = 0
                                   For ctr As Integer = 1 To 1000000
                                      sum += ctr
                                   Next
                                   Return sum
                                End Function)
      Dim syncTask As New Task(Of Long)( Function()
                                            Console.WriteLine("Task {0} (syncTask) executing on Thread {1}",
                                                              Task.CurrentId,
                                                              Thread.CurrentThread.ManagedThreadId)
                                            Dim sum As Long = 0
                                            For ctr As Integer = 1 To 1000000
                                               sum += ctr
                                            Next
                                            Return sum
                                         End Function)
      syncTask.RunSynchronously()
      Console.WriteLine()
      Console.WriteLine("Task {0} returned {1:N0}", syncTask.Id, syncTask.Result)
      Console.WriteLine("Task {0} returned {1:N0}", asyncTask.Id, asyncTask.Result)
   End Sub
End Module
' The example displays the following output:
'       Application executing on thread 1
'       Task 1 (syncTask) executing on Thread 1
'       Task 2 (asyncTask) executing on Thread 3
'       1 status: RanToCompletion
'       2 status: RanToCompletion
'
'       Task 2 returned 500,000,500,000
'       Task 1 returned 500,000,500,000

Comentários

Normalmente, as tarefas são executadas de forma assíncrona em um thread do pool de threads e não bloqueiam o thread de chamada.Ordinarily, tasks are executed asynchronously on a thread pool thread and do not block the calling thread. As tarefas executadas chamando o método RunSynchronously() são associadas ao @no__t atual-1 e são executadas no thread de chamada.Tasks executed by calling the RunSynchronously() method are associated with the current TaskScheduler and are run on the calling thread. Se o Agendador de destino não oferecer suporte à execução dessa tarefa no thread de chamada, a tarefa será agendada para execução no Agendador, e o thread de chamada será bloqueado até que a tarefa tenha concluído a execução.If the target scheduler does not support running this task on the calling thread, the task will be scheduled for execution on the scheduler, and the calling thread will block until the task has completed execution. Embora a tarefa seja executada de forma síncrona, o thread de chamada ainda deve chamar Wait para lidar com as exceções que a tarefa pode gerar.Even though the task runs synchronously, the calling thread should still call Wait to handle any exceptions that the task might throw. Para obter mais informações sobre manipulação de exceção, consulte tratamento de exceção.For more information on exception handling, see Exception Handling.

As tarefas executadas chamando o método RunSynchronously são instanciadas chamando um construtor de classe Task ou Task<TResult>.Tasks executed by calling the RunSynchronously method are instantiated by calling a Task or Task<TResult> class constructor. A tarefa a ser executada de forma síncrona deve estar no estado Created.The task to be run synchronously must be in the Created state. Uma tarefa pode ser iniciada e executada apenas uma vez.A task may be started and run only once. Qualquer tentativa de agendar uma tarefa na segunda vez resulta em uma exceção.Any attempts to schedule a task a second time results in an exception.

Veja também

RunSynchronously(TaskScheduler)

Executa o Task de forma síncrona no TaskScheduler fornecido.Runs the Task synchronously on the TaskScheduler provided.

public:
 void RunSynchronously(System::Threading::Tasks::TaskScheduler ^ scheduler);
public void RunSynchronously (System.Threading.Tasks.TaskScheduler scheduler);
member this.RunSynchronously : System.Threading.Tasks.TaskScheduler -> unit
Public Sub RunSynchronously (scheduler As TaskScheduler)

Parâmetros

scheduler
TaskScheduler

O agendador no qual haverá a tentativa de executar essa tarefa embutida.The scheduler on which to attempt to run this task inline.

Exceções

A instância Task foi descartada.The Task instance has been disposed.

O argumento scheduler é null.The scheduler argument is null.

O Task não está em um estado válido para ser iniciado.The Task is not in a valid state to be started. Ele pode já ter sido iniciado, executado ou cancelado ou pode ter sido criado de forma a não dar suporte ao agendamento direto.It may have already been started, executed, or canceled, or it may have been created in a manner that doesn't support direct scheduling.

Comentários

As tarefas executadas chamando o método RunSynchronously são instanciadas chamando um construtor de classe Task ou Task<TResult>.Tasks executed by calling the RunSynchronously method are instantiated by calling a Task or Task<TResult> class constructor. A tarefa a ser executada de forma síncrona deve estar no estado Created.The task to be run synchronously must be in the Created state. Uma tarefa pode ser iniciada e executada apenas uma vez.A task may be started and run only once. Qualquer tentativa de agendar uma tarefa na segunda vez resulta em uma exceção.Any attempts to schedule a task a second time results in an exception.

Se o Agendador de destino não oferecer suporte à execução dessa tarefa no thread atual, a tarefa será agendada para execução no Agendador, e o thread atual será bloqueado até que a tarefa tenha concluído a execução.If the target scheduler does not support running this task on the current thread, the task will be scheduled for execution on the scheduler, and the current thread will block until the task has completed execution. Por isso, o thread de chamada não precisa chamar um método como Wait para garantir que a tarefa tenha concluído a execução.Because of this, the calling thread does not need to call a method such as Wait to ensure that the task has completed execution. Para obter mais informações sobre a manipulação de exceção para operações de tarefa, consulte manipulação de exceção.For more information on exception handling for task operations, see Exception Handling.

Veja também

Aplica-se a