Partager via


Bibliothèque parallèle de tâches et programmation asynchrone .NET traditionnelle

Le .NET Framework fournit les deux modèles standard suivants pour l'exécution d'opérations asynchrones liées aux E/S et orientées ordinateur :

  • Le modèle de programmation asynchrone, dans lequel les opérations asynchrones sont représentées par une paire de méthodes Begin/End telles que FileStream.BeginRead et Stream.EndRead.

  • Le modèle asynchrone basé sur des événements, dans lequel les opérations asynchrones sont représentées par une paire méthode/événement nommés NomOpérationAsync et NomOpérationCompleted, par exemple, WebClient.DownloadStringAsync et WebClient.DownloadStringCompleted (le modèle asynchrone basé sur des événements a été introduit avec le .NET Framework version 2.0).

La bibliothèque parallèle de tâches peut être utilisée de plusieurs façons conjointement à l'un ou l'autre des modèles asynchrones. Il est possible d'exposer à la fois les opérations de modèle de programmation asynchrone et de modèle asynchrone basé sur des événements en tant que Tâches aux consommateurs de la bibliothèque et d'exposer des modèles de programmation asynchrone et utiliser des objets Task pour les implémenter en interne. Dans les deux scénarios, en utilisant des objets Task, vous pouvez simplifier le code et bénéficier des fonctionnalités utiles suivantes :

  • Enregistrer des rappels sous la forme de continuations de tâches, à tout moment après le lancement de la tâche ;

  • Coordonner plusieurs opérations qui s'exécutent en réponse à une méthode Begin_, à l'aide des méthodes ContinueWhenAll et ContinueWhenAny, ou des méthodes WaitAll ou WaitAny ;

  • Encapsuler des opérations asynchrones liées aux E/S et orientées ordinateur dans le même objet Task ;

  • Surveiller l'état de l'objet Task ;

  • Marshaler le statut d'une opération sur un objet Task à l'aide de TaskCompletionSource<TResult>.

Encapsulation d'opérations de modèle de programmation asynchrone dans une tâche

Les classes System.Threading.Tasks.TaskFactory et System.Threading.Tasks.TaskFactory<TResult> fournissent plusieurs surcharges de la méthode FromAsync et FromAsync qui vous permettent d'encapsuler une paire de méthodes de modèle de programmation asynchrone Begin/End dans une instance Task ou Task<TResult>. Les différentes surcharges s'adaptent à toutes les paires de méthode Begin/End possédant de zéro à trois paramètres d'entrée.

Pour les paires ayant des méthodes End qui retournent une valeur (Function en Visual Basic), utilisez les méthodes de TaskFactory<TResult>, qui créent un Task<TResult>. Pour les méthodes End qui retournent void (Sub en Visual Basic), utilisez les méthodes de TaskFactory, qui créent un Task.

Pour les rares cas dans lesquels la méthode Begin a plus de trois paramètres ou contient les paramètres ref ou out, les surcharges FromAsync supplémentaires qui encapsulent uniquement la méthode End sont fournies.

L'exemple de code suivant montre la signature de la surcharge qui correspond aux méthodes FromAsync, FileStream.BeginRead et FileStream.EndRead. Cette surcharge prend trois paramètres d'entrée, comme suit.

Public Function FromAsync(Of TArg1, TArg2, TArg3)(
                ByVal beginMethod As Func(Of TArg1, TArg2, TArg3, AsyncCallback, Object, IAsyncResult),
                ByVal endMethod As Func(Of IAsyncResult, TResult),
                ByVal dataBuffer As TArg1,
                ByVal byteOffsetToStartAt As TArg2,
                ByVal maxBytesToRead As TArg3,
                ByVal stateInfo As Object)
public Task<TResult> FromAsync<TArg1, TArg2, TArg3>(
    Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod, //BeginRead
     Func<IAsyncResult, TResult> endMethod, //EndRead
     TArg1 arg1, // the byte[] buffer
     TArg2 arg2, // the offset in arg1 at which to start writing data
     TArg3 arg3, // the maximum number of bytes to read
     object state // optional state information
    ) 

Le premier paramètre est un délégué Func<T1, T2, T3, T4, T5, TResult> qui correspond à la signature de la méthode FileStream.BeginRead. Le deuxième paramètre est un délégué Func<T, TResult> qui prend un IAsyncResult et retourne un TResult. Étant donné que EndRead retourne un entier, le compilateur déduit le type de TResult en tant que Int32 et le type de la tâche en tant que Task<Int32>. Les quatre derniers paramètres sont identiques à ceux de la méthode FileStream.BeginRead :

  • Tampon dans lequel stocker les données de fichiers.

  • Dans le tampon, offset à partir duquel commencer l'écriture des données.

  • Quantité maximale de données à lire dans le fichier.

  • Objet facultatif qui stocke les données d'état définies par l'utilisateur pour passer au rappel.

Utilisation de ContinueWith pour les fonctionnalités de rappel

Si vous devez accéder aux données d'un fichier, et non juste au nombre d'octets, la méthode FromAsync n'est pas suffisante. Utilisez plutôt la méthode Task<String>, dont la propriété Result contient des données de fichier. Pour cela, ajoutez une continuation à la tâche d'origine. La continuation exécute le travail exécuté en général par le délégué AsyncCallback. Elle est appelée lorsque l'antécédent est terminé et les tampons de données remplis. (l'objet FileStream doit être fermé avant le retour)

L'exemple suivant indique comment retourner un Task<String> qui encapsule la paire BeginRead/EndRead de la classe FileStream.

Const MAX_FILE_SIZE As Integer = 14000000
Shared Function GetFileStringAsync(ByVal path As String) As Task(Of String)
    Dim fi As New FileInfo(path)
    Dim data(fi.Length) As Byte

    Dim fs As FileStream = New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, data.Length, True)

    ' Task(Of Integer) returns the number of bytes read
    Dim myTask As Task(Of Integer) = Task(Of Integer).Factory.FromAsync(
        AddressOf fs.BeginRead, AddressOf fs.EndRead, data, 0, data.Length, Nothing)

    ' It is possible to do other work here while waiting
    ' for the antecedent task to complete.
    ' ...

    ' Add the continuation, which returns a Task<string>. 
    Return myTask.ContinueWith(Function(antecedent)
                                   fs.Close()
                                   If (antecedent.Result < 100) Then
                                       Return "Data is too small to bother with."
                                   End If
                                   ' If we did not receive the entire file, the end of the
                                   ' data buffer will contain garbage.
                                   If (antecedent.Result < data.Length) Then
                                       Array.Resize(data, antecedent.Result)
                                   End If

                                   ' Will be returned in the Result property of the Task<string>
                                   ' at some future point after the asynchronous file I/O operation completes.
                                   Return New UTF8Encoding().GetString(data)
                               End Function)

End Function
const int MAX_FILE_SIZE = 14000000;
public static Task<string> GetFileStringAsync(string path)
{
    FileInfo fi = new FileInfo(path);
    byte[] data = null;
    data = new byte[fi.Length];

    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, data.Length, true);

    //Task<int> returns the number of bytes read
    Task<int> task = Task<int>.Factory.FromAsync(
            fs.BeginRead, fs.EndRead, data, 0, data.Length, null);

    // It is possible to do other work here while waiting
    // for the antecedent task to complete.
    // ...

    // Add the continuation, which returns a Task<string>. 
    return task.ContinueWith((antecedent) =>
    {
        fs.Close();

        // Result = "number of bytes read" (if we need it.)
        if (antecedent.Result < 100)
        {
            return "Data is too small to bother with.";
        }
        else
        {
            // If we did not receive the entire file, the end of the
            // data buffer will contain garbage.
            if (antecedent.Result < data.Length)
                Array.Resize(ref data, antecedent.Result);

            // Will be returned in the Result property of the Task<string>
            // at some future point after the asynchronous file I/O operation completes.
            return new UTF8Encoding().GetString(data);
        }
    });
}

La méthode peut alors être appelée, comme suit.

Dim myTask As Task(Of String) = GetFileStringAsync(path)

' Do some other work
' ...

Try
    Console.WriteLine(myTask.Result.Substring(0, 500))
Catch ex As AggregateException
    Console.WriteLine(ex.InnerException.Message)
End Try

Task<string> t = GetFileStringAsync(path);          

// Do some other work:
// ...

try
{
     Console.WriteLine(t.Result.Substring(0, 500));
}
catch (AggregateException ae)
{
    Console.WriteLine(ae.InnerException.Message);
}            

Fourniture de données d'état personnalisées

Dans les opérations IAsyncResult typiques, si votre délégué AsyncCallback a besoin de certaines données d'état personnalisées, vous devez le passer via le dernier paramètre de la méthode Begin, afin que les données puissent être empaquetées dans l'objet IAsyncResult qui est finalement passé à la méthode de rappel. Cela n'est en général pas obligatoire lorsque les méthodes FromAsync sont utilisées. Si les données personnalisées sont connues de la continuation, elles peuvent être capturées directement dans le délégué de continuation. L'exemple suivant ressemble à l'exemple précédent, mais au lieu d'examiner la propriété Result de la tâche antérieure, la continuation examine les données d'état personnalisées directement accessibles au délégué utilisateur de la continuation.

Public Function GetFileStringAsync2(ByVal path As String) As Task(Of String)
    Dim fi = New FileInfo(path)
    Dim data(fi.Length) As Byte
    Dim state As New MyCustomState()

    Dim fs As New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, data.Length, True)
    ' We still pass null for the last parameter because
    ' the state variable is visible to the continuation delegate.
    Dim myTask As Task(Of Integer) = Task(Of Integer).Factory.FromAsync(
            AddressOf fs.BeginRead, AddressOf fs.EndRead, data, 0, data.Length, Nothing)

    Return myTask.ContinueWith(Function(antecedent)
                                   fs.Close()
                                   ' Capture custom state data directly in the user delegate.
                                   ' No need to pass it through the FromAsync method.
                                   If (state.StateData.Contains("New York, New York")) Then
                                       Return "Start spreading the news!"
                                   End If

                                   ' If we did not receive the entire file, the end of the
                                   ' data buffer will contain garbage.
                                   If (antecedent.Result < data.Length) Then
                                       Array.Resize(data, antecedent.Result)
                                   End If
                                   '/ Will be returned in the Result property of the Task<string>
                                   '/ at some future point after the asynchronous file I/O operation completes.
                                   Return New UTF8Encoding().GetString(data)
                               End Function)

End Function
public Task<string> GetFileStringAsync2(string path)
{             
    FileInfo fi = new FileInfo(path);
    byte[] data = new byte[fi.Length];                       
    MyCustomState state = GetCustomState();
    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, data.Length, true);
    // We still pass null for the last parameter because
    // the state variable is visible to the continuation delegate.
    Task<int> task = Task<int>.Factory.FromAsync(
            fs.BeginRead, fs.EndRead, data, 0, data.Length, null);

    return task.ContinueWith((antecedent) =>
    {
        // It is safe to close the filestream now.
        fs.Close();

        // Capture custom state data directly in the user delegate.
        // No need to pass it through the FromAsync method.
        if (state.StateData.Contains("New York, New York"))
        {
            return "Start spreading the news!";
        }
        else
        {
            // If we did not receive the entire file, the end of the
            // data buffer will contain garbage.
            if (antecedent.Result < data.Length)
                Array.Resize(ref data, antecedent.Result);

            // Will be returned in the Result property of the Task<string>
            // at some future point after the asynchronous file I/O operation completes.
            return new UTF8Encoding().GetString(data);
        }
    });

}

Synchronisation de plusieurs tâches FromAsync

Les méthodes ContinueWhenAll et ContinueWhenAny statiques fournissent une flexibilité supplémentaire en cas d'utilisation avec les méthodes FromAsync. L'exemple suivant indique comment initialiser plusieurs opérations d'E/S asynchrones et attendre qu'elles soient toutes terminées avant d'exécuter la continuation.

Public Function GetMultiFileData(ByVal filesToRead As String()) As Task(Of String)
    Dim fs As FileStream
    Dim tasks(filesToRead.Length) As Task(Of String)
    Dim fileData() As Byte = Nothing
    For i As Integer = 0 To filesToRead.Length
        fileData(&H1000) = New Byte()
        fs = New FileStream(filesToRead(i), FileMode.Open, FileAccess.Read, FileShare.Read, fileData.Length, True)

        ' By adding the continuation here, the 
        ' Result of each task will be a string.
        tasks(i) = Task(Of Integer).Factory.FromAsync(AddressOf fs.BeginRead,
                                                      AddressOf fs.EndRead,
                                                      fileData,
                                                      0,
                                                      fileData.Length,
                                                      Nothing).
                                                  ContinueWith(Function(antecedent)
                                                                   fs.Close()
                                                                   'If we did not receive the entire file, the end of the
                                                                   ' data buffer will contain garbage.
                                                                   If (antecedent.Result < fileData.Length) Then
                                                                       ReDim Preserve fileData(antecedent.Result)
                                                                   End If

                                                                   'Will be returned in the Result property of the Task<string>
                                                                   ' at some future point after the asynchronous file I/O operation completes.
                                                                   Return New UTF8Encoding().GetString(fileData)
                                                               End Function)
    Next

    Return Task(Of String).Factory.ContinueWhenAll(tasks, Function(data)

                                                              ' Propagate all exceptions and mark all faulted tasks as observed.
                                                              Task.WaitAll(data)

                                                              ' Combine the results from all tasks.
                                                              Dim sb As New StringBuilder()
                                                              For Each t As Task(Of String) In data
                                                                  sb.Append(t.Result)
                                                              Next
                                                              ' Final result to be returned eventually on the calling thread.
                                                              Return sb.ToString()
                                                          End Function)
End Function
public Task<string> GetMultiFileData(string[] filesToRead)
{
    FileStream fs;
    Task<string>[] tasks = new Task<string>[filesToRead.Length];
    byte[] fileData = null;
    for (int i = 0; i < filesToRead.Length; i++)
    {
        fileData = new byte[0x1000];
        fs = new FileStream(filesToRead[i], FileMode.Open, FileAccess.Read, FileShare.Read, fileData.Length, true);

        // By adding the continuation here, the 
        // Result of each task will be a string.
        tasks[i] = Task<int>.Factory.FromAsync(
                 fs.BeginRead, fs.EndRead, fileData, 0, fileData.Length, null)
                 .ContinueWith((antecedent) =>
                     {
                         fs.Close();

                         // If we did not receive the entire file, the end of the
                         // data buffer will contain garbage.
                         if (antecedent.Result < fileData.Length)
                             Array.Resize(ref fileData, antecedent.Result);

                         // Will be returned in the Result property of the Task<string>
                         // at some future point after the asynchronous file I/O operation completes.
                         return new UTF8Encoding().GetString(fileData);
                     });
    }

    // Wait for all tasks to complete. 
    return Task<string>.Factory.ContinueWhenAll(tasks, (data) =>
    {
        // Propagate all exceptions and mark all faulted tasks as observed.
        Task.WaitAll(data);

        // Combine the results from all tasks.
        StringBuilder sb = new StringBuilder();
        foreach (var t in data)
        {
            sb.Append(t.Result);
        }
        // Final result to be returned eventually on the calling thread.
        return sb.ToString();
    });

}

Tâches FromAsync pour la méthode End uniquement

Pour les rares cas dans lesquels la méthode Begin requiert plus de trois paramètres d'entrée ou a des paramètres ref ou out, vous pouvez utiliser les surcharges FromAsync, telles que TaskFactory<TResult>.FromAsync(IAsyncResult, Func<IAsyncResult, TResult>), qui représentent uniquement la méthode End. Ces méthodes peuvent également être utilisées pour tous les scénarios dans lesquels vous est passé un IAsyncResult que vous voulez encapsuler dans une tâche.

Shared Function ReturnTaskFromAsyncResult() As Task(Of String)
    Dim ar As IAsyncResult = DoSomethingAsynchronously()
    Dim t As Task(Of String) = Task(Of String).Factory.FromAsync(ar, Function(res) CStr(res.AsyncState))
    Return t
End Function
static Task<String> ReturnTaskFromAsyncResult()
{
    IAsyncResult ar = DoSomethingAsynchronously();
    Task<String> t = Task<string>.Factory.FromAsync(ar, _ =>
        {
            return (string)ar.AsyncState;
        });

    return t;
}

Lancement et annulation de tâches FromAsync

La tâche retournée par une méthode FromAsync a l'état WaitingForActivation et sera lancée à un moment donné par le système après la création de la tâche. Si vous essayez d'appeler Start pour une telle tâche, une exception sera levée.

Vous ne pouvez pas annuler de tâche FromAsync, car les API .NET Framework sous-jacentes ne prennent actuellement pas en charge l'annulation en cours de fichiers ou d'E/S réseau. Vous pouvez ajouter des fonctionnalités d'annulation à une méthode qui encapsule un appel FromAsync, mais vous pouvez répondre uniquement à l'annulation avant que FromAsync soit appelé ou terminé (dans une tâche de continuation, par exemple).

Certaines classes prenant en charge le modèle asynchrone basé sur des événements comme par exemple WebClient, prennent en charge l'annulation et vous permet d'intégrer ces fonctionnalités d'annulation native à l'aide des jetons d'annulation.

Exposition d'opérations complexes de modèle asynchrone basé sur des événements en tant que tâches

La bibliothèque parallèle de tâches ne fournit pas de méthodes conçues spécifiquement pour encapsuler une opération asynchrone basée sur des événements de la même façon que la famille FromAsync de méthodes encapsule le modèle IAsyncResult. Toutefois, la bibliothèque parallèle de tâches fournit la classe System.Threading.Tasks.TaskCompletionSource<TResult>, qui peut être utilisée pour représenter tout ensemble d'opérations arbitraire tel qu'un Task<TResult>. Les opérations peuvent être synchrones ou asynchrones et peuvent être liées aux E/S ou orientées ordinateur, ou les deux.

L'exemple suivant indique comment utiliser un TaskCompletionSource<TResult> pour exposer un ensemble d'opérations WebClient asynchrones à du code client en tant que Task de base. Cette méthode vous permet d'entrer un tableau d'URL Web et un terme ou nom à rechercher, puis retourne le nombre d'occurrences de ce terme ou nom sur chaque site.

Class SimpleWebExample
    Dim tcs As New TaskCompletionSource(Of String())
    Dim nameToSearch As String
    Dim token As CancellationToken
    Dim results As New List(Of String)
    Dim m_lock As Object
    Dim count As Integer
    Dim addresses() As String

    Public Function GetWordCountsSimplified(ByVal urls() As String, ByVal str As String, ByVal token As CancellationToken) As Task(Of String())

        Dim webClients() As WebClient
        ReDim webClients(urls.Length)

        ' If the user cancels the CancellationToken, then we can use the
        ' WebClient's ability to cancel its own async operations.
        token.Register(Sub()
                           For Each wc As WebClient In webClients
                               If Not wc Is Nothing Then
                                   wc.CancelAsync()
                               End If
                           Next
                       End Sub)


        For i As Integer = 0 To urls.Length
            webClients(i) = New WebClient()

            ' Specify the callback for the DownloadStringCompleted
            ' event that will be raised by this WebClient instance.
            AddHandler webClients(i).DownloadStringCompleted, AddressOf WebEventHandler

            Dim address As New Uri(urls(i))
            ' Pass the address, and also use it for the userToken 
            ' to identify the page when the delegate is invoked.
            webClients(i).DownloadStringAsync(address, address)
        Next

        ' Return the underlying Task. The client code
        ' waits on the Result property, and handles exceptions
        ' in the try-catch block there.
        Return tcs.Task
    End Function

    Public Sub WebEventHandler(ByVal sender As Object, ByVal args As DownloadStringCompletedEventArgs)

        If args.Cancelled = True Then
            tcs.TrySetCanceled()
            Return
        ElseIf Not args.Error Is Nothing Then
            tcs.TrySetException(args.Error)
            Return
        Else
            ' Split the string into an array of words,
            ' then count the number of elements that match
            ' the search term.
            Dim words() As String = args.Result.Split(" "c)
            Dim NAME As String = nameToSearch.ToUpper()
            Dim nameCount = (From word In words.AsParallel()
                            Where word.ToUpper().Contains(NAME)
                            Select word).Count()

            ' Associate the results with the url, and add new string to the array that 
            ' the underlying Task object will return in its Result property.
            results.Add(String.Format("{0} has {1} instances of {2}", args.UserState, nameCount, NAME))
        End If

        SyncLock (m_lock)
            count = count + 1
            If (count = addresses.Length) Then
                tcs.TrySetResult(results.ToArray())
            End If
        End SyncLock
    End Sub
End Class
Task<string[]> GetWordCountsSimplified(string[] urls, string name, CancellationToken token)
{
    TaskCompletionSource<string[]> tcs = new TaskCompletionSource<string[]>();
    WebClient[] webClients = new WebClient[urls.Length];
    object m_lock = new object();
    int count = 0;
    List<string> results = new List<string>();

    // If the user cancels the CancellationToken, then we can use the
    // WebClient's ability to cancel its own async operations.
    token.Register(() =>
    {
        foreach (var wc in webClients)
        {
            if (wc != null)
                wc.CancelAsync();
        }
    });


    for (int i = 0; i < urls.Length; i++)
    {
        webClients[i] = new WebClient();

        #region callback
        // Specify the callback for the DownloadStringCompleted
        // event that will be raised by this WebClient instance.
        webClients[i].DownloadStringCompleted += (obj, args) =>
        {

            // Argument validation and exception handling omitted for brevity.

            // Split the string into an array of words,
            // then count the number of elements that match
            // the search term.
            string[] words = args.Result.Split(' ');
            string NAME = name.ToUpper();
            int nameCount = (from word in words.AsParallel()
                             where word.ToUpper().Contains(NAME)
                             select word)
                            .Count();

            // Associate the results with the url, and add new string to the array that 
            // the underlying Task object will return in its Result property.
            results.Add(String.Format("{0} has {1} instances of {2}", args.UserState, nameCount, name));

            // If this is the last async operation to complete,
            // then set the Result property on the underlying Task.
            lock (m_lock)
            {
                count++;
                if (count == urls.Length)
                {
                    tcs.TrySetResult(results.ToArray());
                }
            }
        };
        #endregion

        // Call DownloadStringAsync for each URL.
        Uri address = null;
        address = new Uri(urls[i]);
        webClients[i].DownloadStringAsync(address, address);

    } // end for

    // Return the underlying Task. The client code
    // waits on the Result property, and handles exceptions
    // in the try-catch block there.
    return tcs.Task;
}

Pour obtenir un exemple plus complet, incluant la gestion des exceptions et indiquant comment appeler la méthode depuis le code client, consultez Comment : exposer des modèles EAP à l'aide d'une tâche.

Souvenez-vous que toute tâche créée par un TaskCompletionSource<TResult> sera lancée par ce TaskCompletionSource et que, par conséquent, le code utilisateur ne doit pas appeler la méthode Start dans cette tâche.

Implémentation du modèle de programmation asynchrone à l'aide de tâches

Dans certains scénarios, il peut être souhaitable d'exposer directement le modèle IAsyncResult à l'aide des paires de méthodes Begin/End dans une API. Vous pouvez, par exemple, maintenir la cohérence avec les API existantes ou posséder des outils automatisés qui nécessitent ce modèle. Dans de tels cas, vous pouvez utiliser des tâches pour simplifier l'implémentation en interne du modèle de programmation asynchrone.

L'exemple suivant indique comment utiliser des tâches pour implémenter une paire de méthodes de modèle de programmation asynchrone Begin/End pour une méthode orientée ordinateur de longue durée.

Class Calculator
    Public Function BeginCalculate(ByVal decimalPlaces As Integer, ByVal ac As AsyncCallback, ByVal state As Object) As IAsyncResult
        Console.WriteLine("Calling BeginCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId)
        Dim myTask = Task(Of String).Factory.StartNew(Function(obj) Compute(decimalPlaces), state)
        myTask.ContinueWith(Sub(antedecent) ac(myTask))

    End Function
    Private Function Compute(ByVal decimalPlaces As Integer)
        Console.WriteLine("Calling compute on thread {0}", Thread.CurrentThread.ManagedThreadId)

        ' Simulating some heavy work.
        Thread.SpinWait(500000000)

        ' Actual implemenation left as exercise for the reader.
        ' Several examples are available on the Web.
        Return "3.14159265358979323846264338327950288"
    End Function

    Public Function EndCalculate(ByVal ar As IAsyncResult) As String
        Console.WriteLine("Calling EndCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId)
        Return CType(ar, Task(Of String)).Result
    End Function
End Class

Class CalculatorClient
    Shared decimalPlaces As Integer
    Shared Sub Main()
        Dim calc As New Calculator
        Dim places As Integer = 35
        Dim callback As New AsyncCallback(AddressOf PrintResult)
        Dim ar As IAsyncResult = calc.BeginCalculate(places, callback, calc)

        ' Do some work on this thread while the calulator is busy.
        Console.WriteLine("Working...")
        Thread.SpinWait(500000)
        Console.ReadLine()
    End Sub

    Public Shared Sub PrintResult(ByVal result As IAsyncResult)
        Dim c As Calculator = CType(result.AsyncState, Calculator)
        Dim piString As String = c.EndCalculate(result)
        Console.WriteLine("Calling PrintResult on thread {0}; result = {1}",
                   Thread.CurrentThread.ManagedThreadId, piString)
    End Sub

End Class
class Calculator
{
    public IAsyncResult BeginCalculate(int decimalPlaces, AsyncCallback ac, object state)
    {
        Console.WriteLine("Calling BeginCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId);
        Task<string> f = Task<string>.Factory.StartNew(_ => Compute(decimalPlaces), state);
        if (ac != null) f.ContinueWith((res) => ac(f));
        return f;
    }

    public string Compute(int numPlaces)
    {
        Console.WriteLine("Calling compute on thread {0}", Thread.CurrentThread.ManagedThreadId);

        // Simulating some heavy work.
        Thread.SpinWait(500000000);

        // Actual implemenation left as exercise for the reader.
        // Several examples are available on the Web.
        return "3.14159265358979323846264338327950288";
    }

    public string EndCalculate(IAsyncResult ar)
    {
        Console.WriteLine("Calling EndCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId);
        return ((Task<string>)ar).Result;
    }
}

public class CalculatorClient
{
    static int decimalPlaces = 12;
    public static void Main()
    {
        Calculator calc = new Calculator();
        int places = 35;

        AsyncCallback callBack = new AsyncCallback(PrintResult);
        IAsyncResult ar = calc.BeginCalculate(places, callBack, calc);

        // Do some work on this thread while the calulator is busy.
        Console.WriteLine("Working...");
        Thread.SpinWait(500000);
        Console.ReadLine();
    }

    public static void PrintResult(IAsyncResult result)
    {
        Calculator c = (Calculator)result.AsyncState;
        string piString = c.EndCalculate(result);
        Console.WriteLine("Calling PrintResult on thread {0}; result = {1}",
                    Thread.CurrentThread.ManagedThreadId, piString);
    }
}

Utilisation de l'exemple de code StreamExtensions

Le fichier Streamextensions.cs dans Exemples de programmation parallèle avec .NET Framework 4 (page éventuellement en anglais) sur le site MSDN, contient plusieurs implémentations de référence qui utilisent des objets Task pour les fichiers asynchrones et E/S réseau.

Voir aussi

Concepts

Bibliothèque parallèle de tâches