Task.RunSynchronously Metodo

Definizione

Esegue Task in modo sincrono nell'oggetto TaskScheduler corrente.

Overload

RunSynchronously(TaskScheduler)

Esegue Task in modo sincrono nell'oggetto TaskScheduler fornito.

RunSynchronously()

Esegue Task in modo sincrono nell'oggetto TaskScheduler corrente.

RunSynchronously(TaskScheduler)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Esegue Task in modo sincrono nell'oggetto TaskScheduler fornito.

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)

Parametri

scheduler
TaskScheduler

Utilità di pianificazione in cui provare a eseguire questa attività inline.

Eccezioni

L’istanza di Task è stata eliminata.

Il valore dell'argomento scheduler è null.

Task non è in uno stato valido per essere avviato. Potrebbe essere già stato avviato, eseguito o annullato oppure potrebbe essere stato creato in un modo che non supporta la pianificazione diretta.

Commenti

Le attività eseguite chiamando il metodo vengono create un'istanza RunSynchronously chiamando un Task costruttore o Task<TResult> di classe. L'attività Created da eseguire in modo sincrono deve essere nello stato. Un'attività può essere avviata ed eseguita una sola volta. Tutti i tentativi di pianificare un'attività una seconda volta generano un'eccezione.

Se l'utilità di pianificazione di destinazione non supporta l'esecuzione di questa attività nel thread corrente, l'attività verrà pianificata per l'esecuzione nell'utilità di pianificazione e il thread corrente verrà bloccato fino al completamento dell'esecuzione dell'attività. A causa di questo, il thread chiamante non deve chiamare un metodo, ad Wait esempio per assicurarsi che l'attività abbia completato l'esecuzione. Per altre informazioni sulla gestione delle eccezioni per le operazioni di attività, vedere Gestione delle eccezioni.

Vedi anche

Si applica a

RunSynchronously()

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Esegue Task in modo sincrono nell'oggetto TaskScheduler corrente.

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

Eccezioni

L’istanza di Task è stata eliminata.

Task non è in uno stato valido per essere avviato. Potrebbe essere già stato avviato, eseguito o annullato oppure potrebbe essere stato creato in un modo che non supporta la pianificazione diretta.

Esempio

Nell'esempio seguente viene confrontata un'attività eseguita chiamando il RunSynchronously metodo con uno eseguito in modo asincrono. In entrambi i casi, le attività eseguono espressioni lambda identiche che visualizzano l'ID attività e l'ID del thread in cui è in esecuzione l'attività. L'attività calcola la somma dei numeri interi compresi tra 1 e 1.000.000. Come illustrato dall'output dell'esempio, l'attività eseguita chiamando il RunSynchronously metodo viene eseguito nel thread dell'applicazione, mentre l'attività asincrona non viene eseguita.

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
open System
open System.Threading
open System.Threading.Tasks

printfn $"Application executing on thread {Thread.CurrentThread.ManagedThreadId}"

let asyncTask =
    Task.Run(fun () ->
        printfn $"Task {Task.CurrentId} (asyncTask) executing on Thread {Thread.CurrentThread.ManagedThreadId}"
        let mutable sum = 0L

        for i = 1 to 1000000 do
            sum <- sum + int64 i

        sum)

let syncTask =
    new Task<int64>(fun () ->
        printfn $"Task {Task.CurrentId} (syncTask) executing on Thread {Thread.CurrentThread.ManagedThreadId}"
        let mutable sum = 0L

        for i = 1 to 1000000 do
            sum <- sum + int64 i

        sum)

syncTask.RunSynchronously()
printfn $"\nTask {syncTask.Id} returned {syncTask.Result:N0}"
printfn $"Task {asyncTask.Id} returned {asyncTask.Result:N0}"

// 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

Commenti

In genere, le attività vengono eseguite in modo asincrono in un thread del pool di thread e non bloccano il thread chiamante. Le attività eseguite chiamando il RunSynchronously() metodo sono associate all'oggetto corrente TaskScheduler e vengono eseguite nel thread chiamante. Se l'utilità di pianificazione di destinazione non supporta l'esecuzione di questa attività nel thread chiamante, l'attività verrà pianificata per l'esecuzione nell'utilità di pianificazione e il thread chiamante bloccherà fino al completamento dell'esecuzione dell'attività. Anche se l'attività viene eseguita in modo sincrono, il thread chiamante deve comunque chiamare Wait per gestire eventuali eccezioni che l'attività potrebbe generare. Per altre informazioni sulla gestione delle eccezioni, vedere Gestione delle eccezioni.

Le attività eseguite chiamando il metodo vengono create un'istanza RunSynchronously chiamando un Task costruttore o Task<TResult> di classe. L'attività Created da eseguire in modo sincrono deve essere nello stato. Un'attività può essere avviata ed eseguita una sola volta. Tutti i tentativi di pianificare un'attività una seconda volta generano un'eccezione.

Vedi anche

Si applica a