Partilhar via


A TPL e tradicionais.NET programação assíncrona

A.NET Framework fornece os seguintes padrões de padrão de dois para realizar as operações assíncronas vinculada à-/ S e o limite de computação:

  • APM Asynchronous Programming Model (), na qual as operações assíncronas são representadas por um par de métodos Begin/End, como FileStream.BeginRead e Stream.EndRead.

  • Evento padrão assíncrono baseado (EAP), na qual as operações assíncronas são representadas por um par de método/evento é nomeado OperationNameassíncrono e OperationNameconcluída, por exemplo, WebClient.DownloadStringAsync e WebClient.DownloadStringCompleted. (EAP foi introduzido na.NET Framework versão 2.0).

A tarefa paralela TPL (biblioteca) pode ser usado de várias maneiras em conjunto com um dos padrões assíncronos. Você pode expor as operações de APM e o EAP como tarefas aos consumidores de biblioteca, ou você pode expor os padrões APM mas usar objetos de tarefa para implementá-los internamente. Em ambos os cenários, usando objetos de tarefa, você pode simplificar o código e aproveitar as seguintes funcionalidades úteis:

  • Registre retornos de chamada, na forma de continuação da tarefa, a qualquer momento após a tarefa foi iniciada.

  • Coordenar as várias operações executadas em resposta a uma Begin_ método, usando o ContinueWhenAll e ContinueWhenAny métodos, ou o WaitAll método ou a WaitAny método.

  • Encapsule operações assíncronas de vinculada à-/ S e vinculado aos computadores no mesmo objeto de tarefa.

  • Monitore o status do objeto de tarefa.

  • Empacotar o status de uma operação para um objeto de tarefa usando TaskCompletionSource<TResult>.

Operações de APM de quebra automática em uma tarefa

Tanto o System.Threading.Tasks.TaskFactory e System.Threading.Tasks.TaskFactory<TResult> classes fornecem várias sobrecargas daFromAsync eFromAsyncmétodos que permitem encapsulam um par de métodos de APM Begin/End em um Task instância ou Task<TResult> instância. As várias sobrecargas acomodam qualquer par de método Begin/End têm de zero a três parâmetros de entrada.

Para pares de tem End métodos que retornam um valor (Function em Visual Basic), os métodos usados no TaskFactory<TResult>, que cria uma Task<TResult>. Para End métodos retornam void (Sub em Visual Basic), use os métodos em TaskFactory, que cria uma Task.

Para esses poucos casos em que o Begin tem mais de três parâmetros de método ou contém ref ou out parâmetros adicionais FromAsync sobrecargas que encapsulam apenas o End método são fornecidos.

O exemplo de código a seguir mostra a assinatura para o FromAsync sobrecarga que corresponde a FileStream.BeginRead e FileStream.EndRead métodos. Essa sobrecarga tem três parâmetros de entrada, como segue.

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
    ) 

O primeiro parâmetro é um Func<T1, T2, T3, T4, T5, TResult> delegado que corresponde à assinatura da FileStream.BeginRead método. O segundo parâmetro é um Func<T, TResult> representante que leva um IAsyncResult e retorna um TResult. Porque EndRead retorna um inteiro, o compilador infere o tipo de TResult como Int32 e o tipo da tarefa como Task<Int32>. Os quatro últimos parâmetros são idênticos do FileStream.BeginRead método:

  • O buffer para armazenar os dados do arquivo.

  • O deslocamento em buffer no qual começar a gravar dados.

  • A quantidade máxima de dados para ler o arquivo.

  • Um objeto opcional que armazena dados de estado definido pelo usuário para passar para o retorno de chamada.

Usando o ContinueWith para a funcionalidade de retorno de chamada

Se você precisar acessar os dados no arquivo, em oposição a apenas o número de bytes, o FromAsync método não é suficiente. Em vez disso, use Task<String>, cujo Result propriedade contém o arquivo de dados. Você pode fazer isso adicionando uma continuação da tarefa original. A continuação realiza o trabalho que normalmente seria realizado pela AsyncCallback delegate. Ele é invocado quando antecedent é concluída e o buffer de dados foram preenchidos. (O FileStream objeto deve ser fechado antes de retornar.)

O exemplo a seguir mostra como retornar um Task<String> que encapsula o par de BeginRead/EndRead da FileStream classe.

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);
        }
    });
}

O método pode então ser chamado, como segue.

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);
}            

Fornecer dados de estado personalizado

Típicas IAsyncResult operações, se sua AsyncCallback representante requer alguns dados de estado personalizado, você precisa passá-lo no último parâmetro na Begin método, para que os dados podem ser empacotados na IAsyncResult objeto eventualmente, que é passado para o método de retorno de chamada. Isso geralmente não é necessário quando o FromAsync métodos são usados. Se os dados personalizados são conhecidos como a continuação, ele pode ser capturado diretamente no delegado continuação. O exemplo a seguir semelhante ao exemplo anterior, mas em vez de examinar o Result a propriedade de antecedent, continuação examina os dados de estado personalizado que é acessíveis diretamente para o representante do usuário da continuação.

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);
        }
    });

}

A sincronização de várias tarefas de FromAsync

Estática ContinueWhenAll e ContinueWhenAny métodos fornecem maior flexibilidade quando usado em conjunto com o FromAsync métodos. O exemplo a seguir mostra como iniciar várias operações de e/S assíncronas e espere para todos eles para concluir antes de executar a continuação.

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();
    });

}

Tarefas de FromAsync para o método de fim

Para esses poucos casos em que o Begin método requer mais de três parâmetros de entrada, ou tem ref ou out parâmetros, você pode usar o FromAsync sobrecargas, por exemplo, TaskFactory<TResult>.FromAsync(IAsyncResult, Func<IAsyncResult, TResult>), que representam apenas o End método. Esses métodos também podem ser usados em qualquer cenário em que são passados um IAsyncResult e deseja encapsulá-lo em uma tarefa.

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;
}

Iniciando e Cancelando tarefas de FromAsync

A tarefa retornada por uma FromAsync método tem um status de WaitingForActivation e será iniciado pelo sistema em algum momento após a criação da tarefa. Se você tentar chamar Start em tal tarefa, uma exceção será gerada.

Você não pode cancelar uma tarefa deFromAsync , porque o subjacente.APIs do NET Framework no momento não oferece suporte ao cancelamento de em andamento do arquivo ou de rede e/S. Você pode adicionar a funcionalidade de cancelamento para um método que encapsula um FromAsync chamada, mas você só poderá responder para o cancelamento antes de FromAsync é chamado ou depois dela concluída (por exemplo, em uma tarefa de continuação).

Algumas classes que oferecem suporte a EAP, por exemplo, WebClient, oferece suporte ao cancelamento, e você pode integrar essa funcionalidade de cancelamento nativo usando tokens de cancelamento.

Expondo operações complexas de EAP, como tarefas

A TPL não fornece quaisquer métodos que são projetados especificamente para encapsular uma operação assíncrona baseada em eventos da mesma maneira que o FromAsync da família de quebra automática de métodos de IAsyncResult padrão. No entanto, a TPL fornecem a System.Threading.Tasks.TaskCompletionSource<TResult> classe, que pode ser usado para representar qualquer conjunto arbitrário de operações como um Task<TResult>. As operações podem ser síncrono ou assíncrono e podem ser vinculado de e/S, vinculado aos computadores ou ambos.

O exemplo a seguir mostra como usar um TaskCompletionSource<TResult> para expor um conjunto de assíncrono WebClient as operações de código do cliente como um basic Task. O método permite que você insira uma matriz de URLs de Web e um termo ou nome para procurar e, em seguida, retorna o número de vezes que o termo de pesquisa ocorre em cada 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;
}

Para um exemplo mais completo, que inclui a manipulação de exceção adicionais e mostra como chamar o método do código de cliente, consulte Como: Encapsular o EAP padrões em uma tarefa.

Lembre-se de que qualquer tarefa que é criado por um TaskCompletionSource<TResult> será iniciado por que TaskCompletionSource e, portanto, o código do usuário não deve chamar o método Start na tarefa.

Implementando o padrão APM usando as tarefas

Em algumas situações, pode ser desejável para expor diretamente o IAsyncResult padrão usando pares de método Begin/End em uma API. Por exemplo, talvez você queira manter a consistência com as APIs existentes, ou ter automatizada ferramentas que exigem esse padrão. Em tais casos, você pode usar tarefas para simplificar a como o padrão APM é implementado internamente.

O exemplo a seguir mostra como usar tarefas para implementar um par de método de APM Begin/End para um método de associadas à computação de execução demorada.

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);
    }
}

Usando o código de exemplo de StreamExtensions

Arquivo de Streamextensions.cs, em amostras depara programação paralela com o.NET Framework 4 no site do MSDN, contém várias implementações de referência que usam objetos de tarefa para o arquivo assíncrono e e/S de rede.

Consulte também

Conceitos

Biblioteca paralela de tarefas