Task Classe

Définition

Représente une opération asynchrone.

public ref class Task : IAsyncResult
public ref class Task : IAsyncResult, IDisposable
public class Task : IAsyncResult
public class Task : IAsyncResult, IDisposable
type Task = class
    interface IAsyncResult
type Task = class
    interface IAsyncResult
    interface IDisposable
Public Class Task
Implements IAsyncResult
Public Class Task
Implements IAsyncResult, IDisposable
Héritage
Task
Dérivé
Implémente

Remarques

La Task classe représente une seule opération qui ne retourne pas de valeur et qui s’exécute généralement de manière asynchrone. Task les objets sont l’un des composants centraux du modèle asynchrone basé sur les tâches introduit pour la première fois dans .NET Framework 4. Étant donné que le travail effectué par un Task objet s’exécute généralement de manière asynchrone sur un thread de pool de threads plutôt que de manière synchrone sur le thread d’application principal, vous pouvez utiliser la Status propriété, ainsi que les IsCanceledpropriétés , IsCompletedet IsFaulted , pour déterminer l’état d’une tâche. Le plus souvent, une expression lambda est utilisée pour spécifier le travail que la tâche doit effectuer.

Pour les opérations qui retournent des valeurs, vous utilisez la Task<TResult> classe .

Dans cette section :

Exemples d’instanciation de tâche
Création et exécution d’une tâche
Séparation de la création et de l’exécution des tâches
En attente de l’exécution d’une ou de plusieurs tâches
Tâches et culture
Pour les développeurs de débogueur

Instanciation de tâche

L’exemple suivant crée et exécute quatre tâches. Trois tâches exécutent un Action<T> délégué nommé action, qui accepte un argument de type Object. Une quatrième tâche exécute une expression lambda (un Action délégué) définie inline dans l’appel à la méthode de création de tâche. Chaque tâche est instanciée et exécutée d’une manière différente :

  • La tâche t1 est instanciée en appelant un constructeur de classe Task, mais n’est démarrée en appelant sa Start() méthode qu’après le démarrage de la tâche t2 .

  • La tâche t2 est instanciée et démarrée dans un seul appel de méthode en appelant la TaskFactory.StartNew(Action<Object>, Object) méthode.

  • La tâche t3 est instanciée et démarrée dans un seul appel de méthode en appelant la Run(Action) méthode.

  • La tâche t4 est exécutée de manière synchrone sur le thread principal en appelant la RunSynchronously() méthode .

Étant donné que la tâche t4 s’exécute de manière synchrone, elle s’exécute sur le thread d’application principal. Les tâches restantes s’exécutent généralement de manière asynchrone sur un ou plusieurs threads de pool de threads.

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

class Example
{
    static void Main()
    {
        Action<object> action = (object obj) =>
                                {
                                   Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                   Task.CurrentId, obj,
                                   Thread.CurrentThread.ManagedThreadId);
                                };

        // Create a task but do not start it.
        Task t1 = new Task(action, "alpha");

        // Construct a started task
        Task t2 = Task.Factory.StartNew(action, "beta");
        // Block the main thread to demonstrate that t2 is executing
        t2.Wait();

        // Launch t1 
        t1.Start();
        Console.WriteLine("t1 has been launched. (Main Thread={0})",
                          Thread.CurrentThread.ManagedThreadId);
        // Wait for the task to finish.
        t1.Wait();

        // Construct a started task using Task.Run.
        String taskData = "delta";
        Task t3 = Task.Run( () => {Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                                     Task.CurrentId, taskData,
                                                      Thread.CurrentThread.ManagedThreadId);
                                   });
        // Wait for the task to finish.
        t3.Wait();

        // Construct an unstarted task
        Task t4 = new Task(action, "gamma");
        // Run it synchronously
        t4.RunSynchronously();
        // Although the task was run synchronously, it is a good practice
        // to wait for it in the event exceptions were thrown by the task.
        t4.Wait();
    }
}
// The example displays output like the following:
//       Task=1, obj=beta, Thread=3
//       t1 has been launched. (Main Thread=1)
//       Task=2, obj=alpha, Thread=4
//       Task=3, obj=delta, Thread=3
//       Task=4, obj=gamma, Thread=1
open System.Threading
open System.Threading.Tasks

let action =
    fun (obj: obj) -> printfn $"Task={Task.CurrentId}, obj={obj}, Thread={Thread.CurrentThread.ManagedThreadId}"

// Create a task but do not start it.
let t1 = new Task(action, "alpha")

// Construct a started task
let t2 = Task.Factory.StartNew(action, "beta")
// Block the main thread to demonstrate that t2 is executing
t2.Wait()

// Launch t1
t1.Start()
printfn $"t1 has been launched. (Main Thread={Thread.CurrentThread.ManagedThreadId})"
// Wait for the task to finish.
t1.Wait()

// Construct a started task using Task.Run.
let taskData = "delta"

let t3 =
    Task.Run(fun () -> printfn $"Task={Task.CurrentId}, obj={taskData}, Thread={Thread.CurrentThread.ManagedThreadId}")
// Wait for the task to finish.
t3.Wait()

// Construct an unstarted task
let t4 = new Task(action, "gamma")
// Run it synchronously
t4.RunSynchronously()
// Although the task was run synchronously, it is a good practice
// to wait for it in the event exceptions were thrown by the task.
t4.Wait()


// The example displays output like the following:
//       Task=1, obj=beta, Thread=3
//       t1 has been launched. (Main Thread=1)
//       Task=2, obj=alpha, Thread=4
//       Task=3, obj=delta, Thread=3
//       Task=4, obj=gamma, Thread=1
Imports System.Threading
Imports System.Threading.Tasks

Module Example
    Public Sub Main()
        Dim action As Action(Of Object) = 
              Sub(obj As Object)
                 Console.WriteLine("Task={0}, obj={1}, Thread={2}", 
                 Task.CurrentId, obj,
                 Thread.CurrentThread.ManagedThreadId)
              End Sub

        ' Construct an unstarted task
        Dim t1 As New Task(action, "alpha")

        ' Construct a started task
        Dim t2 As Task = Task.Factory.StartNew(action, "beta")
        ' Block the main thread to demonstrate that t2 is executing
        t2.Wait()

        ' Launch t1 
        t1.Start()
        Console.WriteLine("t1 has been launched. (Main Thread={0})",
                          Thread.CurrentThread.ManagedThreadId)
        ' Wait for the task to finish.
        t1.Wait()

        ' Construct a started task using Task.Run.
        Dim taskData As String = "delta"
        Dim t3 As Task = Task.Run(Sub()
                                     Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                     Task.CurrentId, taskData,
                                     Thread.CurrentThread.ManagedThreadId)
                                  End Sub)
        ' Wait for the task to finish.
        t3.Wait()
        
        ' Construct an unstarted task
        Dim t4 As New Task(action, "gamma")
        ' Run it synchronously
        t4.RunSynchronously()
        ' Although the task was run synchronously, it is a good practice
        ' to wait for it in the event exceptions were thrown by the task.
        t4.Wait()
    End Sub
End Module
' The example displays output like the following:
'       Task=1, obj=beta, Thread=3
'       t1 has been launched. (Main Thread=1)
'       Task=2, obj=alpha, Thread=3
'       Task=3, obj=delta, Thread=3
'       Task=4, obj=gamma, Thread=1

Création et exécution d’une tâche

Task les instances peuvent être créées de différentes manières. L’approche la plus courante, disponible à partir de .NET Framework 4.5, consiste à appeler la méthode statique Run . La Run méthode fournit un moyen simple de démarrer une tâche à l’aide de valeurs par défaut et sans nécessiter de paramètres supplémentaires. L’exemple suivant utilise la Run(Action) méthode pour démarrer une tâche qui effectue des boucles, puis affiche le nombre d’itérations de boucle :

using System;
using System.Threading.Tasks;

public class Example
{
   public static async Task Main()
   {
      await Task.Run( () => {
                                  // Just loop.
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
   }
}
// The example displays the following output:
//        Finished 1000001 loop iterations
open System.Threading.Tasks

let main =
    task {
        do!
            Task.Run(fun () ->
                for i = 0 to 1000000 do
                    printfn $"Finished {i} loop iterations")
    }

main.Wait()

// The example displays the following output:
//        Finished 1000001 loop iterations
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim t As Task = Task.Run(Sub()
                                  ' Just loop.
                                  Dim ctr As Integer = 0
                                  For ctr = 0 to 1000000
                                  Next
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr)
                               End Sub)
      t.Wait()
   End Sub
End Module
' The example displays the following output:
'       Finished 1000001 loop iterations

Une autre méthode, et la méthode la plus courante pour démarrer une tâche dans .NET Framework 4, est la méthode statique TaskFactory.StartNew . La Task.Factory propriété retourne un TaskFactory objet. Les surcharges de la TaskFactory.StartNew méthode vous permettent de spécifier des paramètres à passer aux options de création de tâches et à un planificateur de tâches. L’exemple suivant utilise la TaskFactory.StartNew méthode pour démarrer une tâche. Elle est fonctionnellement équivalente au code de l’exemple précédent.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Factory.StartNew( () => {
                                  // Just loop.
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
      t.Wait();
   }
}
// The example displays the following output:
//        Finished 1000001 loop iterations
open System.Threading.Tasks

let t =
    Task.Factory.StartNew(fun () ->
        // Just loop.
        for i = 0 to 1000000 do
            printfn $"Finished {i} loop iterations")

t.Wait()


// The example displays the following output:
//        Finished 1000001 loop iterations
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim t As Task = Task.Factory.StartNew(Sub()
                                  ' Just loop.
                                  Dim ctr As Integer = 0
                                  For ctr = 0 to 1000000
                                  Next
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr)
                               End Sub)
      t.Wait()
   End Sub
End Module
' The example displays the following output:
'       Finished 1000001 loop iterations

Pour obtenir des exemples plus complets, consultez Programmation asynchrone basée sur les tâches.

Séparation de la création et de l’exécution des tâches

La Task classe fournit également des constructeurs qui initialisent la tâche, mais qui ne la planifient pas pour l’exécution. Pour des raisons de performances, la Task.Run méthode ou TaskFactory.StartNew est le mécanisme préféré pour créer et planifier des tâches de calcul, mais pour les scénarios où la création et la planification doivent être séparées, vous pouvez utiliser les constructeurs, puis appeler la Task.Start méthode pour planifier l’exécution de la tâche ultérieurement.

En attente de l’exécution d’une ou de plusieurs tâches

Étant donné que les tâches s’exécutent généralement de manière asynchrone sur un thread de pool de threads, le thread qui crée et démarre la tâche continue l’exécution dès que la tâche a été instanciée. Dans certains cas, lorsque le thread appelant est le thread d’application principal, l’application peut se terminer avant que la tâche ne commence réellement son exécution. Dans d’autres cas, la logique de votre application peut exiger que le thread appelant continue l’exécution uniquement lorsqu’une ou plusieurs tâches ont terminé l’exécution. Vous pouvez synchroniser l’exécution du thread appelant et les tâches asynchrones qu’il lance en appelant une Wait méthode pour attendre qu’une ou plusieurs tâches se terminent.

Pour attendre qu’une seule tâche se termine, vous pouvez appeler sa Task.Wait méthode. Un appel à la méthode bloque le Wait thread appelant jusqu’à ce que l’instance de classe unique ait terminé l’exécution.

L’exemple suivant appelle la méthode sans Wait() paramètre pour attendre inconditionnellement jusqu’à ce qu’une tâche se termine. La tâche simule le travail en appelant la méthode à mettre en Thread.Sleep veille pendant deux secondes.

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

class Program
{
    static Random rand = new Random();

    static void Main()
    {
        // Wait on a single task with no timeout specified.
        Task taskA = Task.Run( () => Thread.Sleep(2000));
        Console.WriteLine("taskA Status: {0}", taskA.Status);
        try {
          taskA.Wait();
          Console.WriteLine("taskA Status: {0}", taskA.Status);
       } 
       catch (AggregateException) {
          Console.WriteLine("Exception in taskA.");
       }   
    }    
}
// The example displays output like the following:
//     taskA Status: WaitingToRun
//     taskA Status: RanToCompletion
open System
open System.Threading
open System.Threading.Tasks

let rand = Random()

// Wait on a single task with no timeout specified.
let taskA = Task.Run(fun () -> Thread.Sleep 2000)
printfn $"taskA Status: {taskA.Status}"
try 
    taskA.Wait()
    printfn $"taskA Status: {taskA.Status}"

with :? AggregateException ->
    printfn "Exception in taskA."

// The example displays output like the following:
//     taskA Status: WaitingToRun
//     taskA Status: RanToCompletion
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ' Wait on a single task with no timeout specified.
      Dim taskA = Task.Run( Sub() Thread.Sleep(2000))
      Console.WriteLine("taskA Status: {0}", taskA.Status)
      Try
        taskA.Wait()
        Console.WriteLine("taskA Status: {0}", taskA.Status)
      Catch e As AggregateException
         Console.WriteLine("Exception in taskA.")
      End Try
   End Sub
End Module
' The example displays output like the following:
'     taskA Status: WaitingToRun
'     taskA Status: RanToCompletion

Vous pouvez également attendre de manière conditionnelle qu’une tâche se termine. Les Wait(Int32) méthodes et Wait(TimeSpan) bloquent le thread appelant jusqu’à la fin de la tâche ou jusqu’à ce qu’un délai d’expiration s’écoule, selon la première éventualité. Étant donné que l’exemple suivant lance une tâche qui se met en veille pendant deux secondes, mais définit une valeur de délai d’expiration d’une seconde, le thread appelant se bloque jusqu’à l’expiration du délai d’expiration et avant que la tâche n’ait terminé l’exécution.

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

public class Example
{
   public static void Main()
   {
      // Wait on a single task with a timeout specified.
      Task taskA = Task.Run( () => Thread.Sleep(2000));
      try {
        taskA.Wait(1000);       // Wait for 1 second.
        bool completed = taskA.IsCompleted;
        Console.WriteLine("Task A completed: {0}, Status: {1}",
                         completed, taskA.Status);
        if (! completed)
           Console.WriteLine("Timed out before task A completed.");                 
       }
       catch (AggregateException) {
          Console.WriteLine("Exception in taskA.");
       }   
   }
}
// The example displays output like the following:
//     Task A completed: False, Status: Running
//     Timed out before task A completed.
open System
open System.Threading
open System.Threading.Tasks

// Wait on a single task with a timeout specified.
let taskA = Task.Run(fun () -> Thread.Sleep 2000)

try
    taskA.Wait 1000 |> ignore // Wait for 1 second.
    let completed = taskA.IsCompleted
    printfn $"Task A completed: {completed}, Status: {taskA.Status}"

    if not completed then
        printfn "Timed out before task A completed."

with :? AggregateException ->
    printfn "Exception in taskA."


// The example displays output like the following:
//     Task A completed: False, Status: Running
//     Timed out before task A completed.
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ' Wait on a single task with a timeout specified.
      Dim taskA As Task = Task.Run( Sub() Thread.Sleep(2000))
      Try
         taskA.Wait(1000)        ' Wait for 1 second.
         Dim completed As Boolean = taskA.IsCompleted
         Console.WriteLine("Task.Completed: {0}, Status: {1}",
                           completed, taskA.Status)
         If Not completed Then 
            Console.WriteLine("Timed out before task A completed.")
         End If                     
      Catch e As AggregateException
         Console.WriteLine("Exception in taskA.")
      End Try
   End Sub
End Module
' The example displays the following output:
'     Task A completed: False, Status: Running
'     Timed out before task A completed.

Vous pouvez également fournir un jeton d’annulation en appelant les Wait(CancellationToken) méthodes et Wait(Int32, CancellationToken) . Si la propriété du jeton est true ou devient true pendant l’exécution de la Wait méthode, la méthode lève un OperationCanceledException.IsCancellationRequested

Dans certains cas, vous pouvez attendre la fin de la première d’une série de tâches en cours d’exécution, mais ne vous souciez pas de la tâche qu’il s’agit. À cet effet, vous pouvez appeler l’une des surcharges de la Task.WaitAny méthode. L’exemple suivant crée trois tâches, dont chacune est mise en veille pour un intervalle déterminé par un générateur de nombres aléatoires. La WaitAny(Task[]) méthode attend la fin de la première tâche. L’exemple affiche ensuite des informations sur l’état des trois tâches.

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

public class Example
{
   public static void Main()
   {
      var tasks = new Task[3];
      var rnd = new Random();
      for (int ctr = 0; ctr <= 2; ctr++)
         tasks[ctr] = Task.Run( () => Thread.Sleep(rnd.Next(500, 3000)));

      try {
         int index = Task.WaitAny(tasks);
         Console.WriteLine("Task #{0} completed first.\n", tasks[index].Id);
         Console.WriteLine("Status of all tasks:");
         foreach (var t in tasks)
            Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
      }
      catch (AggregateException) {
         Console.WriteLine("An exception occurred.");
      }
   }
}
// The example displays output like the following:
//     Task #1 completed first.
//     
//     Status of all tasks:
//        Task #3: Running
//        Task #1: RanToCompletion
//        Task #4: Running
open System
open System.Threading
open System.Threading.Tasks

let rnd = new Random()

let tasks =
    [| for _ = 0 to 2 do
           Task.Run(fun () -> rnd.Next(500, 3000) |> Thread.Sleep) |]

try
    let index = Task.WaitAny tasks
    printfn $"Task #{tasks[index].Id} completed first.\n"
    printfn "Status of all tasks:"

    for t in tasks do
        printfn $"   Task #{t.Id}: {t.Status}"

with :? AggregateException ->
    printfn "An exception occurred."

// The example displays output like the following:
//     Task #1 completed first.
//
//     Status of all tasks:
//        Task #3: Running
//        Task #1: RanToCompletion
//        Task #4: Running
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks(2) As Task
      Dim rnd As New Random()
      For ctr As Integer = 0 To 2
         tasks(ctr) = Task.Run( Sub()  Thread.Sleep(rnd.Next(500, 3000)))
      Next
      
      Try 
         Dim index As Integer= Task.WaitAny(tasks)
         Console.WriteLine("Task #{0} completed first.", tasks(index).Id)
         Console.WriteLine()
         Console.WriteLine("Status of all tasks:")
         For Each t in tasks
            Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status)
         Next   
      Catch e As AggregateException
         Console.WriteLine("An exception occurred.")
      End Try
   End Sub
End Module
' The example displays output like the following:
'     Task #1 completed first.
'     
'     Status of all tasks:
'        Task #3: Running
'        Task #1: RanToCompletion
'        Task #4: Running

Vous pouvez également attendre que toutes les tâches se terminent en appelant la WaitAll méthode . L’exemple suivant crée dix tâches, attend que toutes les dix se terminent, puis affiche leur état.

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

public class Example
{
   public static void Main()
   {
      // Wait for all tasks to complete.
      Task[] tasks = new Task[10];
      for (int i = 0; i < 10; i++)
      {
          tasks[i] = Task.Run(() => Thread.Sleep(2000));
      }
      try {
         Task.WaitAll(tasks);
      }
      catch (AggregateException ae) {
         Console.WriteLine("One or more exceptions occurred: ");
         foreach (var ex in ae.Flatten().InnerExceptions)
            Console.WriteLine("   {0}", ex.Message);
      }   

      Console.WriteLine("Status of completed tasks:");
      foreach (var t in tasks)
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
   }
}
// The example displays the following output:
//     Status of completed tasks:
//        Task #2: RanToCompletion
//        Task #1: RanToCompletion
//        Task #3: RanToCompletion
//        Task #4: RanToCompletion
//        Task #6: RanToCompletion
//        Task #5: RanToCompletion
//        Task #7: RanToCompletion
//        Task #8: RanToCompletion
//        Task #9: RanToCompletion
//        Task #10: RanToCompletion
open System
open System.Threading
open System.Threading.Tasks

// Wait for all tasks to complete.
let tasks =
    [| for _ = 0 to 9 do
           Task.Run(fun () -> Thread.Sleep 2000) |]

try
    Task.WaitAll tasks

with :? AggregateException as ae ->
    printfn "One or more exceptions occurred: "

    for ex in ae.Flatten().InnerExceptions do
        printfn $"   {ex.Message}"

printfn "Status of completed tasks:"

for t in tasks do
    printfn $"   Task #{t.Id}: {t.Status}"

// The example displays the following output:
//     Status of completed tasks:
//        Task #2: RanToCompletion
//        Task #1: RanToCompletion
//        Task #3: RanToCompletion
//        Task #4: RanToCompletion
//        Task #6: RanToCompletion
//        Task #5: RanToCompletion
//        Task #7: RanToCompletion
//        Task #8: RanToCompletion
//        Task #9: RanToCompletion
//        Task #10: RanToCompletion
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ' Wait for all tasks to complete.
      Dim tasks(9) As Task
      For i As Integer = 0 To 9
          tasks(i) = Task.Run( Sub() Thread.Sleep(2000) )
      Next
      Try 
         Task.WaitAll(tasks)
      Catch ae As AggregateException
         Console.WriteLine("One or more exceptions occurred: ")
         For Each ex In ae.Flatten().InnerExceptions
            Console.WriteLine("   {0}", ex.Message)
         Next
      End Try   

      Console.WriteLine("Status of completed tasks:")
      For Each t in tasks
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status)
      Next   
   End Sub
End Module
' The example displays the following output:
'     Status of completed tasks:
'        Task #2: RanToCompletion
'        Task #1: RanToCompletion
'        Task #3: RanToCompletion
'        Task #4: RanToCompletion
'        Task #6: RanToCompletion
'        Task #5: RanToCompletion
'        Task #7: RanToCompletion
'        Task #8: RanToCompletion
'        Task #9: RanToCompletion
'        Task #10: RanToCompletion

Notez que lorsque vous attendez qu’une ou plusieurs tâches se terminent, toutes les exceptions levées dans les tâches en cours d’exécution sont propagées sur le thread qui appelle la méthode, comme le Wait montre l’exemple suivant. Il lance 12 tâches, dont trois se terminent normalement et trois d’entre elles lèvent une exception. Sur les six tâches restantes, trois sont annulées avant leur début et trois sont annulées pendant leur exécution. Les exceptions sont levées dans l’appel de WaitAll méthode et sont gérées par un try/catch bloc.

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

public class Example
{
   public static void Main()
   {
      // Create a cancellation token and cancel it.
      var source1 = new CancellationTokenSource();
      var token1 = source1.Token;
      source1.Cancel();
      // Create a cancellation token for later cancellation.
      var source2 = new CancellationTokenSource();
      var token2 = source2.Token;
       
      // Create a series of tasks that will complete, be cancelled, 
      // timeout, or throw an exception.
      Task[] tasks = new Task[12];
      for (int i = 0; i < 12; i++)
      {
          switch (i % 4) 
          {
             // Task should run to completion.
             case 0:
                tasks[i] = Task.Run(() => Thread.Sleep(2000));
                break;
             // Task should be set to canceled state.
             case 1:   
                tasks[i] = Task.Run( () => Thread.Sleep(2000),
                         token1);
                break;         
             case 2:
                // Task should throw an exception.
                tasks[i] = Task.Run( () => { throw new NotSupportedException(); } );
                break;
             case 3:
                // Task should examine cancellation token.
                tasks[i] = Task.Run( () => { Thread.Sleep(2000); 
                                             if (token2.IsCancellationRequested)
                                                token2.ThrowIfCancellationRequested();
                                             Thread.Sleep(500); }, token2);   
                break;
          }
      }
      Thread.Sleep(250);
      source2.Cancel();
       
      try {
         Task.WaitAll(tasks);
      }
      catch (AggregateException ae) {
          Console.WriteLine("One or more exceptions occurred:");
          foreach (var ex in ae.InnerExceptions)
             Console.WriteLine("   {0}: {1}", ex.GetType().Name, ex.Message);
       }   

      Console.WriteLine("\nStatus of tasks:");
      foreach (var t in tasks) {
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
         if (t.Exception != null) {
            foreach (var ex in t.Exception.InnerExceptions)
               Console.WriteLine("      {0}: {1}", ex.GetType().Name,
                                 ex.Message);
         }
      }
   }
}
// The example displays output like the following:
//   One or more exceptions occurred:
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//   
//   Status of tasks:
//      Task #13: RanToCompletion
//      Task #1: Canceled
//      Task #3: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #8: Canceled
//      Task #14: RanToCompletion
//      Task #4: Canceled
//      Task #6: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #7: Canceled
//      Task #15: RanToCompletion
//      Task #9: Canceled
//      Task #11: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #12: Canceled
open System
open System.Threading
open System.Threading.Tasks

// Create a cancellation token and cancel it.
let source1 = new CancellationTokenSource()
let token1 = source1.Token
source1.Cancel()
// Create a cancellation token for later cancellation.
let source2 = new CancellationTokenSource()
let token2 = source2.Token

// Create a series of tasks that will complete, be cancelled,
// timeout, or throw an exception.
let tasks =
    [| for i in 0..11 do
           match i % 4 with
           // Task should run to completion.
           | 0 -> Task.Run(fun () -> Thread.Sleep 2000)
           // Task should be set to canceled state.
           | 1 -> Task.Run(fun () -> Thread.Sleep 2000, token1)
           // Task should throw an exception.
           | 2 -> Task.Run(fun () -> NotSupportedException())
           // Task should examine cancellation token.
           | _ ->
               Task.Run(fun () ->
                   Thread.Sleep 2000

                   if token2.IsCancellationRequested then
                       token2.ThrowIfCancellationRequested()

                   Thread.Sleep 500, token2) |]


Thread.Sleep 250
source2.Cancel()

try
    Task.WaitAll tasks

with :? AggregateException as ae ->
    printfn "One or more exceptions occurred:"

    for ex in ae.InnerExceptions do
        printfn $"   {ex.GetType().Name}: {ex.Message}"

printfn "\nStatus of tasks:"

for t in tasks do
    printfn $"   Task #{t.Id}: {t.Status}"

    if isNull t.Exception |> not then
        for ex in t.Exception.InnerExceptions do
            printfn $"      {ex.GetType().Name}: {ex.Message}"

// The example displays output like the following:
//   One or more exceptions occurred:
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//
//   Status of tasks:
//      Task #13: RanToCompletion
//      Task #1: Canceled
//      Task #3: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #8: Canceled
//      Task #14: RanToCompletion
//      Task #4: Canceled
//      Task #6: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #7: Canceled
//      Task #15: RanToCompletion
//      Task #9: Canceled
//      Task #11: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #12: Canceled
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ' Create a cancellation token and cancel it.
      Dim source1 As New CancellationTokenSource()
      Dim token1 As CancellationToken = source1.Token
      source1.Cancel()
      ' Create a cancellation token for later cancellation.
      Dim source2 As New CancellationTokenSource()
      Dim token2 As CancellationToken = source2.Token
       
      ' Create a series of tasks that will complete, be cancelled, 
      ' timeout, or throw an exception.
      Dim tasks(11) As Task
      For i As Integer = 0 To 11
          Select Case i Mod 4 
             ' Task should run to completion.
             Case 0
                tasks(i) = Task.Run( Sub() Thread.Sleep(2000))
             ' Task should be set to canceled state.
             Case 1   
                tasks(i) = Task.Run( Sub() Thread.Sleep(2000), token1)
             Case 2
                ' Task should throw an exception.
                tasks(i) = Task.Run( Sub() 
                                        Throw New NotSupportedException() 
                                     End Sub)
             Case 3
                ' Task should examine cancellation token.
                tasks(i) = Task.Run( Sub() 
                                        Thread.Sleep(2000) 
                                        If token2.IsCancellationRequested
                                           token2.ThrowIfCancellationRequested()
                                        End If
                                        Thread.Sleep(500) 
                                     End Sub, token2)   
          End Select
      Next
      Thread.Sleep(250)
      source2.Cancel()
       
      Try 
         Task.WaitAll(tasks)
      Catch ae As AggregateException
         Console.WriteLine("One or more exceptions occurred:")
         For Each ex in ae.InnerExceptions
             Console.WriteLine("   {0}: {1}", ex.GetType().Name, ex.Message)
         Next
      End Try   
      Console.WriteLine()
      
      Console.WriteLine("Status of tasks:")
      For Each t in tasks
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status)
         If t.Exception IsNot Nothing Then
            For Each ex in t.Exception.InnerExceptions
               Console.WriteLine("      {0}: {1}", ex.GetType().Name,
                                 ex.Message)
            Next
         End If
      Next
   End Sub
End Module
' The example displays output like the following:
'   One or more exceptions occurred:
'      TaskCanceledException: A task was canceled.
'      NotSupportedException: Specified method is not supported.
'      TaskCanceledException: A task was canceled.
'      TaskCanceledException: A task was canceled.
'      NotSupportedException: Specified method is not supported.
'      TaskCanceledException: A task was canceled.
'      TaskCanceledException: A task was canceled.
'      NotSupportedException: Specified method is not supported.
'      TaskCanceledException: A task was canceled.
'   
'   Status of tasks:
'      Task #13: RanToCompletion
'      Task #1: Canceled
'      Task #3: Faulted
'         NotSupportedException: Specified method is not supported.
'      Task #8: Canceled
'      Task #14: RanToCompletion
'      Task #4: Canceled
'      Task #6: Faulted
'         NotSupportedException: Specified method is not supported.
'      Task #7: Canceled
'      Task #15: RanToCompletion
'      Task #9: Canceled
'      Task #11: Faulted
'         NotSupportedException: Specified method is not supported.
'      Task #12: Canceled

Pour plus d’informations sur la gestion des exceptions dans les opérations asynchrones basées sur des tâches, consultez Gestion des exceptions.

Tâches et culture

À compter des applications de bureau qui ciblent .NET Framework 4.6, la culture du thread qui crée et appelle une tâche fait partie du contexte du thread. Autrement dit, quelle que soit la culture actuelle du thread sur lequel la tâche s’exécute, la culture actuelle de la tâche est la culture du thread appelant. Pour les applications qui ciblent les versions du .NET Framework antérieures à .NET Framework 4.6, la culture de la tâche est la culture du thread sur lequel la tâche s’exécute. Pour plus d’informations, consultez la section « Culture et opérations asynchrones basées sur les tâches » dans la CultureInfo rubrique.

Notes

Les applications du Store suivent les Windows Runtime dans la définition et l’obtention de la culture par défaut.

Pour les développeurs de débogueur

Pour les développeurs qui implémentent des débogueurs personnalisés, plusieurs membres internes et privés de la tâche peuvent être utiles (ils peuvent changer d’une mise en production à l’autre). Le m_taskId champ sert de magasin de stockage pour la Id propriété, mais l’accès direct à ce champ à partir d’un débogueur peut être plus efficace que l’accès à la même valeur via la méthode getter de la propriété (le s_taskIdCounter compteur est utilisé pour récupérer l’ID disponible suivant pour une tâche). De même, le m_stateFlags champ stocke des informations sur l’étape de cycle de vie actuelle de la tâche, des informations également accessibles via la Status propriété . Le m_action champ stocke une référence au délégué de la tâche, et le m_stateObject champ stocke l’état asynchrone passé à la tâche par le développeur. Enfin, pour les débogueurs qui analysent les trames de pile, la InternalWait méthode sert un marqueur potentiel pour le moment où une tâche entre dans une opération d’attente.

Constructeurs

Task(Action)

Initialise un nouveau Task avec l'action spécifiée.

Task(Action, CancellationToken)

Initialise un nouveau Task avec l'action spécifiée et CancellationToken.

Task(Action, CancellationToken, TaskCreationOptions)

Initialise une nouvelle Task avec l'action et les options de création spécifiées.

Task(Action, TaskCreationOptions)

Initialise une nouvelle Task avec l'action et les options de création spécifiées.

Task(Action<Object>, Object)

Initialise un nouveau Task avec l'action et l'état spécifiés.

Task(Action<Object>, Object, CancellationToken)

Initialise une nouvelle Task avec l'action, l'état et les options spécifiés.

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

Initialise une nouvelle Task avec l'action, l'état et les options spécifiés.

Task(Action<Object>, Object, TaskCreationOptions)

Initialise une nouvelle Task avec l'action, l'état et les options spécifiés.

Propriétés

AsyncState

Obtient l'objet d'état fourni quand la Task a été créée, ou null si aucune n'a été fournie.

CompletedTask

Obtient une tâche qui s’est déjà terminée correctement.

CreationOptions

Obtient les TaskCreationOptions utilisées pour créer cette tâche.

CurrentId

Retourne l'ID de la Task en cours d'exécution.

Exception

Obtient le AggregateException qui a provoqué l'arrêt prématuré de Task. Si la Task s'est terminée avec succès ou n'a pas encore levé d'exception, la valeur null est retournée.

Factory

Fournit l'accès aux méthodes de fabrique pour la création d'instances de Task et de Task<TResult>.

Id

Obtient un ID pour cette instance de Task.

IsCanceled

Indique si cette instance de Task s'est exécutée avec succès suite à une annulation.

IsCompleted

Obtient une valeur indiquant si la tâche est terminée.

IsCompletedSuccessfully

Obtient une valeur indiquant si la tâche s’est exécutée jusqu’à son achèvement.

IsFaulted

Indique si la Task s'est terminée suite à une exception non gérée.

Status

Obtient le TaskStatus de cette tâche.

Méthodes

ConfigureAwait(Boolean)

Configure un élément awaiter utilisé pour attendre cette Task.

ContinueWith(Action<Task,Object>, Object)

Crée une continuation qui reçoit des informations d'état fournies par l'appelant et s'exécute quand le Task cible se termine.

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

Crée une continuation qui reçoit des informations d'état fournies par l'appelant et un jeton d'annulation, et qui s'exécute de façon asynchrone quand le Task cible se termine.

ContinueWith(Action<Task,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)

Crée une continuation qui reçoit des informations d'état fournies par l'appelant et un jeton d'annulation, et qui s'exécute quand le Task cible se termine. La continuation s'exécute selon un ensemble de conditions spécifiées et utilise un planificateur spécifié.

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

Crée une continuation qui reçoit des informations d'état fournies par l'appelant et s'exécute quand le Task cible se termine. La continuation s'exécute selon un ensemble de conditions spécifiées.

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

Crée une continuation qui reçoit des informations d'état fournies par l'appelant et s'exécute de façon asynchrone quand le Task cible se termine. La continuation utilise un planificateur spécifié.

ContinueWith(Action<Task>)

Crée une continuation qui s'exécute de façon asynchrone quand la Task cible se termine.

ContinueWith(Action<Task>, CancellationToken)

Crée une continuation qui reçoit un jeton d'annulation et s'exécute de façon asynchrone quand le Task cible se termine.

ContinueWith(Action<Task>, CancellationToken, TaskContinuationOptions, TaskScheduler)

Crée une continuation qui s’exécute quand la tâche cible se termine conformément au TaskContinuationOptions spécifié. La continuation reçoit un jeton d'annulation et utilise un planificateur spécifié.

ContinueWith(Action<Task>, TaskContinuationOptions)

Crée une continuation qui s’exécute quand la tâche cible se termine conformément au TaskContinuationOptions spécifié.

ContinueWith(Action<Task>, TaskScheduler)

Crée une continuation qui s'exécute de façon asynchrone quand la Task cible se termine. La continuation utilise un planificateur spécifié.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object)

Crée une continuation qui reçoit des informations d'état fournies par l'appelant et s'exécute de façon asynchrone quand le Task cible se termine et retourne une valeur.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken)

Crée une continuation qui s'exécute de façon asynchrone quand le Task cible se termine et retourne une valeur. La continuation reçoit des informations d'état fournies par l'appelant et un jeton d'annulation.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)

Crée une continuation qui s’exécute en fonction des options de continuation de tâche spécifiées quand le Task cible se termine et retourne une valeur. La continuation reçoit des informations d'état fournies par l'appelant et un jeton d'annulation et elle utilise un planificateur spécifié.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskContinuationOptions)

Crée une continuation qui s’exécute en fonction des options de continuation de tâche spécifiées quand le Task cible se termine. La continuation reçoit des informations d'état fournies par l'appelant.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskScheduler)

Crée une continuation qui s'exécute de façon asynchrone quand la Task cible se termine. La continuation reçoit des informations d'état fournies par l'appelant et utilise un planificateur spécifié.

ContinueWith<TResult>(Func<Task,TResult>)

Crée une continuation qui s'exécute de façon asynchrone quand le Task<TResult> cible se termine et retourne une valeur.

ContinueWith<TResult>(Func<Task,TResult>, CancellationToken)

Crée une continuation qui s'exécute de façon asynchrone quand le Task cible se termine et retourne une valeur. La continuation reçoit un jeton d'annulation.

ContinueWith<TResult>(Func<Task,TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)

Crée une continuation qui s'exécute en fonction des options de continuation spécifiées et retourne une valeur. La continuation reçoit un jeton d'annulation et utilise un planificateur spécifié.

ContinueWith<TResult>(Func<Task,TResult>, TaskContinuationOptions)

Crée une continuation qui s'exécute en fonction des options de continuation spécifiées et retourne une valeur.

ContinueWith<TResult>(Func<Task,TResult>, TaskScheduler)

Crée une continuation qui s'exécute de façon asynchrone quand le Task cible se termine et retourne une valeur. La continuation utilise un planificateur spécifié.

Delay(Int32)

Crée une tâche qui se termine après un nombre spécifié de millisecondes.

Delay(Int32, CancellationToken)

Crée une tâche pouvant être annulée qui se termine après un nombre spécifié de millisecondes.

Delay(TimeSpan)

Crée une tâche qui se termine après un intervalle de temps spécifié.

Delay(TimeSpan, CancellationToken)

Crée une tâche pouvant être annulée qui se termine après un intervalle de temps spécifié.

Delay(TimeSpan, TimeProvider)

Représente une opération asynchrone.

Delay(TimeSpan, TimeProvider, CancellationToken)

Représente une opération asynchrone.

Dispose()

Libère toutes les ressources utilisées par l'instance actuelle de la classe Task.

Dispose(Boolean)

Supprime la Task, en libérant toutes ses ressources non managées.

Equals(Object)

Détermine si l'objet spécifié est égal à l'objet actuel.

(Hérité de Object)
FromCanceled(CancellationToken)

Crée une Task qui s'est terminée en raison de l'annulation avec un jeton d'annulation spécifié.

FromCanceled<TResult>(CancellationToken)

Crée une Task<TResult> qui s'est terminée en raison de l'annulation avec un jeton d'annulation spécifié.

FromException(Exception)

Crée une Task qui s'est terminée avec une exception spécifiée.

FromException<TResult>(Exception)

Crée une Task<TResult> qui s'est terminée avec une exception spécifiée.

FromResult<TResult>(TResult)

Crée un Task<TResult> qui s'est terminé avec succès avec le résultat spécifié.

GetAwaiter()

Obtient un élément awaiter utilisé pour attendre cette Task.

GetHashCode()

Fait office de fonction de hachage par défaut.

(Hérité de Object)
GetType()

Obtient le Type de l'instance actuelle.

(Hérité de Object)
MemberwiseClone()

Crée une copie superficielle du Object actuel.

(Hérité de Object)
Run(Action)

Met en file d'attente le travail spécifié à exécuter dans le pool de threads et retourne un objet Task qui représente ce travail.

Run(Action, CancellationToken)

Met en file d'attente le travail spécifié à exécuter dans le pool de threads et retourne un objet Task qui représente ce travail. Un jeton d’annulation permet l’annulation du travail s’il n’a pas encore été commencé.

Run(Func<Task>)

Met en file d’attente le travail spécifié à exécuter sur le pool de threads et retourne un proxy pour la tâche retournée par function.

Run(Func<Task>, CancellationToken)

Met en file d’attente le travail spécifié à exécuter sur le pool de threads et retourne un proxy pour la tâche retournée par function. Un jeton d’annulation permet l’annulation du travail s’il n’a pas encore été commencé.

Run<TResult>(Func<Task<TResult>>)

Met en file d’attente le travail spécifié à exécuter dans le pool de threads et retourne un proxy pour le Task(TResult) retourné par function. Un jeton d’annulation permet l’annulation du travail s’il n’a pas encore été commencé.

Run<TResult>(Func<Task<TResult>>, CancellationToken)

Met en file d’attente le travail spécifié à exécuter dans le pool de threads et retourne un proxy pour le Task(TResult) retourné par function.

Run<TResult>(Func<TResult>)

Met en file d'attente le travail spécifié à exécuter dans le pool de threads et retourne un objet Task<TResult> qui représente ce travail. Un jeton d’annulation permet l’annulation du travail s’il n’a pas encore été commencé.

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

Met en file d'attente le travail spécifié à exécuter dans le pool de threads et retourne un objet Task(TResult) qui représente ce travail.

RunSynchronously()

Exécute de façon synchrone la Task sur le TaskScheduler actuel.

RunSynchronously(TaskScheduler)

Exécute de façon synchrone le Task sur le TaskScheduler fourni.

Start()

Démarre la Task, en planifiant son exécution sur le TaskScheduler actuel.

Start(TaskScheduler)

Démarre la Task, en planifiant son exécution sur le TaskScheduler spécifié.

ToString()

Retourne une chaîne qui représente l'objet actuel.

(Hérité de Object)
Wait()

Attend la fin de l'exécution de Task.

Wait(CancellationToken)

Attend la fin de l'exécution de Task. L'attente se termine si un jeton d'annulation est annulé avant la fin de la tâche.

Wait(Int32)

Attend la fin de l'exécution de la Task en un nombre de millisecondes spécifié.

Wait(Int32, CancellationToken)

Attend la fin de l'exécution de Task. L'attente se termine si un intervalle de délai est écoulé ou si un jeton d'annulation est annulé avant la fin de la tâche.

Wait(TimeSpan)

Attend la fin de l'exécution de la Task dans un intervalle de temps spécifié.

Wait(TimeSpan, CancellationToken)

Attend la fin de l'exécution de Task.

WaitAll(Task[])

Attend la fin de l'exécution de tous les objets Task fournis.

WaitAll(Task[], CancellationToken)

Attend la fin de l'exécution de tous les objets Task fournis sauf si l'attente est annulée.

WaitAll(Task[], Int32)

Attend la fin de l'exécution de tous les objets Task fournis en un nombre de millisecondes spécifié.

WaitAll(Task[], Int32, CancellationToken)

Attend la fin de l'exécution de tous les objets Task fournis en un nombre de millisecondes spécifié ou jusqu'à ce que l'attente soit annulée.

WaitAll(Task[], TimeSpan)

Attend la fin de l'exécution de tous les objets Task pouvant être annulés fournis dans un intervalle de temps spécifié.

WaitAny(Task[])

Attend la fin de l'exécution de l'un des objets Task fournis.

WaitAny(Task[], CancellationToken)

Attend la fin de l'exécution de l'un des objets Task fournis sauf si l'attente est annulée.

WaitAny(Task[], Int32)

Attend la fin de l'exécution de l'un des objets Task fournis en un nombre de millisecondes spécifié.

WaitAny(Task[], Int32, CancellationToken)

Attend la fin de l'exécution de l'un des objets Task fournis en un nombre de millisecondes spécifié ou jusqu'à ce qu'un jeton d'annulation soit annulé.

WaitAny(Task[], TimeSpan)

Attend la fin de l'exécution de n'importe lequel des objets Task fournis dans un intervalle de temps spécifié.

WaitAsync(CancellationToken)

Obtient un Task qui se terminera une fois cette Task opération terminée ou lorsque l’annulation du spécifié a été CancellationToken demandée.

WaitAsync(TimeSpan)

Obtient un Task qui se terminera à l’expiration Task ou à l’expiration du délai d’attente spécifié.

WaitAsync(TimeSpan, CancellationToken)

Obtient un Task qui se terminera une fois cette Task opération terminée, lorsque le délai d’expiration spécifié expire ou lorsque l’annulation spécifiée a été CancellationToken demandée.

WaitAsync(TimeSpan, TimeProvider)

Représente une opération asynchrone.

WaitAsync(TimeSpan, TimeProvider, CancellationToken)

Représente une opération asynchrone.

WhenAll(IEnumerable<Task>)

Crée une tâche qui s’achève quand tous les objets Task d’une collection énumérable sont terminés.

WhenAll(Task[])

Crée une tâche qui s’achève quand tous les objets Task d’un tableau sont terminés.

WhenAll<TResult>(IEnumerable<Task<TResult>>)

Crée une tâche qui s’achève quand tous les objets Task<TResult> d’une collection énumérable sont terminés.

WhenAll<TResult>(Task<TResult>[])

Crée une tâche qui s’achève quand tous les objets Task<TResult> d’un tableau sont terminés.

WhenAny(IEnumerable<Task>)

Crée une tâche qui s'achève lorsque l'une des tâches fournies est terminée.

WhenAny(Task, Task)

Crée une tâche qui se terminera lorsque l’une des tâches fournies est terminée.

WhenAny(Task[])

Crée une tâche qui s'achève lorsque l'une des tâches fournies est terminée.

WhenAny<TResult>(IEnumerable<Task<TResult>>)

Crée une tâche qui s'achève lorsque l'une des tâches fournies est terminée.

WhenAny<TResult>(Task<TResult>, Task<TResult>)

Crée une tâche qui se terminera lorsque l’une des tâches fournies est terminée.

WhenAny<TResult>(Task<TResult>[])

Crée une tâche qui s'achève lorsque l'une des tâches fournies est terminée.

Yield()

Crée une tâche pouvant être attendue qui se produit de manière asynchrone dans le contexte actuel pendant l’attente.

Implémentations d’interfaces explicites

IAsyncResult.AsyncWaitHandle

Obtient un WaitHandle qui peut être utilisé en attendant la fin de la tâche.

IAsyncResult.CompletedSynchronously

Obtient une indication précisant si l’opération s’est terminée de manière synchrone.

Méthodes d’extension

DispatcherOperationWait(Task)

Attend indéfiniment que l'opération DispatcherOperation sous-jacente se termine.

DispatcherOperationWait(Task, TimeSpan)

Attend pendant le délai spécifié que le DispatcherOperation sous-jacente se termine.

IsDispatcherOperationTask(Task)

Retourne une valeur qui indique si cette Task est associée à une DispatcherOperation.

AsAsyncAction(Task)

Retourne une action asynchrone Windows Runtime qui représente une tâche initiée.

S’applique à

Cohérence de thread

Tous les membres de , à l’exception de TaskDispose(), sont thread-safe et peuvent être utilisés simultanément à partir de plusieurs threads.

Voir aussi