Condividi tramite


Task Parallel Library e programmazione asincrona .NET tradizionale

.NET Framework fornisce i due modelli standard seguenti per l'esecuzione di operazioni asincrone con vincoli di I/O e di calcolo:

  • Modello di programmazione asincrono (APM, Asynchronous Programming Model), in cui le operazioni asincrone vengono rappresentate da una coppia di metodi Begin/End quali FileStream.BeginRead e Stream.EndRead.

  • Modello asincrono basato su eventi (EAP, Event-based Asynchronous Pattern), in cui le operazioni asincrone vengono rappresentate da una coppia formata da un metodo e un evento denominati NomeOperazioneAsync e NomeOperazioneCompleted, ad esempio WebClient.DownloadStringAsync e WebClient.DownloadStringCompleted. Il modello EAP è stato introdotto nella versione 2.0 di .NET Framework.

La libreria Task Parallel Library (TPL) può essere utilizzata in vari modi insieme a uno di questi modelli asincroni. È possibile esporre sia operazioni APM sia operazioni EAP come attività ai consumer della libreria. In alternativa, è possibile esporre i modelli APM ma utilizzare oggetti Task per implementarli internamente. In entrambi gli scenari, tramite gli oggetti Task è possibile semplificare il codice e sfruttare le utili funzionalità seguenti:

  • Registrare callback sotto forma di continuazioni di attività in qualsiasi momento successivo all'avvio dell'attività.

  • Coordinare più operazioni che vengono eseguite in risposta a un metodo Begin_, tramite i metodi ContinueWhenAll e ContinueWhenAny o il metodo WaitAll oppure il metodo WaitAny.

  • Incapsulare operazioni asincrone con vincoli di I/O e di calcolo nello stesso oggetto Task.

  • Monitorare lo stato dell'oggetto Task.

  • Eseguire il marshalling dello stato di un'operazione a un oggetto Task tramite TaskCompletionSource<TResult>.

Esecuzione del wrapping di operazioni APM in un'attività

Sia la classe System.Threading.Tasks.TaskFactory che la classe System.Threading.Tasks.TaskFactory<TResult> forniscono diversi overload dei metodiFromAsync eFromAsyncche consentono di incapsulare una coppia di metodi Begin/End APM in un'unica istanza di Task o Task<TResult>. I vari overload consentono di incapsulare qualsiasi coppia di metodi Begin/End aventi da zero a tre parametri di input.

Per le coppie con metodi End che restituiscono un valore (detti metodi Function in Visual Basic), utilizzare i metodi in TaskFactory<TResult> che creano un oggetto Task<TResult>. Per i metodi End che restituiscono void (detti metodi Sub in Visual Basic), utilizzare i metodi in TaskFactory che creano un oggetto Task.

Per quei casi rari in cui il metodo Begin presenta più di tre parametri o contiene parametri ref oppure out vengono forniti overload di FromAsync aggiuntivi che incapsulano solo il metodo End.

Nell'esempio di codice seguente viene mostrata la firma dell'overload di FromAsync che corrisponde ai metodi FileStream.BeginRead e FileStream.EndRead. Questo overload accetta tre parametri di input, come 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
    ) 

Il primo parametro è un delegato Func<T1, T2, T3, T4, T5, TResult> che corrisponde alla firma del metodo FileStream.BeginRead. Il secondo parametro è un delegato Func<T, TResult> che accetta un oggetto IAsyncResult e restituisce un oggetto TResult. Poiché EndRead restituisce un intero, il compilatore deduce che il tipo di TResult è Int32 e che il tipo dell'attività è Task<Int32>. Gli ultimi quattro parametri sono identici a quelli del metodo FileStream.BeginRead:

  • Buffer in cui archiviare i dati di file.

  • Offset nel buffer in corrispondenza del quale iniziare la scrittura dei dati.

  • Quantità massima di dati da leggere dal file.

  • Oggetto facoltativo in cui vengono archiviati i dati sullo stato definito dall'utente da passare al callback.

Utilizzo di ContinueWith per la funzionalità di callback

Se occorre accedere ai dati nel file e non soltanto al numero di byte, il metodo FromAsync non è sufficiente. È invece necessario utilizzare Task<String>, la cui proprietà Result contiene i dati di file. A tale scopo è possibile aggiungere una continuazione all'attività originale. La continuazione esegue le operazioni che in genere vengono eseguite dal delegato AsyncCallback. Viene richiamata quando l'attività precedente viene completata e il buffer di dati è stato riempito. L'oggetto FileStream deve essere chiuso prima della restituzione.

Nell'esempio seguente viene mostrato come restituire un oggetto Task<String> che incapsula la coppia BeginRead/EndRead della 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);
        }
    });
}

È quindi possibile chiamare il metodo, come 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);
}            

Come fornire dati sullo stato personalizzati

Nelle operazioni IAsyncResult tipiche, se il delegato AsyncCallback richiede dati sullo stato personalizzati, è necessario passarli tramite l'ultimo parametro del metodo Begin, in modo che sia possibile raccoglierli nell'oggetto IAsyncResult che alla fine viene passato al metodo di callback. In genere ciò non è necessario quando si utilizzano i metodi FromAsync. Se i dati personalizzati sono noti alla continuazione, è possibile acquisirli direttamente nel delegato di continuazione. L'esempio seguente assomiglia all'esempio precedente, ma anziché esaminare la proprietà Result dell'attività precedente, la continuazione esamina i dati sullo stato personalizzati accessibili direttamente dal delegato dell'utente della continuazione.

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

}

Sincronizzazione di più attività FromAsync

I metodi ContinueWhenAll e ContinueWhenAny statici forniscono maggiore flessibilità quando utilizzati insieme ai metodi FromAsync. Nell'esempio seguente viene mostrato come iniziare più operazioni di I/O asincrone e quindi come attendere il completamento di ognuna di esse prima di eseguire la continuazione.

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

}

Attività FromAsync soltanto per il metodo End

Per quei casi rari in cui il metodo Begin richiede più di tre parametri di input o presenta parametri ref oppure out è possibile utilizzare gli overload di FromAsync, ad esempio TaskFactory<TResult>.FromAsync(IAsyncResult, Func<IAsyncResult, TResult>), che rappresentano solo il metodo End. Questi metodi possono anche essere utilizzati in qualsiasi scenario in cui a un oggetto viene passato un oggetto IAsyncResult che si desidera incapsulare in un'attività.

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

Avvio e annullamento di attività FromAsync

L'attività restituita da un metodo FromAsync presenta lo stato WaitingForActivation e verrà avviata dal sistema in un momento successivo alla creazione dell'attività. Se si tenta di chiamare Start su tale attività, verrà generata un'eccezione.

Non è possibile annullare un'attività FromAsync, poiché attualmente le API di .NET Framework sottostanti non supportano l'annullamento di I/O di file o di rete già in corso. È possibile aggiungere la funzionalità di annullamento a un metodo che incapsula una chiamata FromAsync, ma in questo caso sarà possibile rispondere all'annullamento solo prima che FromAsync venga chiamato o solo dopo che è stato completato (ad esempio, in un'attività di continuazione).

Alcune classi che supportano EAP, ad esempio WebClient, supportano l'annullamento ed è possibile integrare questa funzionalità di annullamento nativa tramite l'utilizzo di token di annullamento.

Esposizione di operazioni EAP complesse come attività

La libreria TPL non fornisce alcun metodo progettato in maniera specifica per incapsulare un'operazione asincrona basata su eventi nello stesso modo in cui la famiglia di metodi FromAsync esegue il wrapping del modello IAsyncResult. Tuttavia, TPL fornisce la classe System.Threading.Tasks.TaskCompletionSource<TResult> che può essere utilizzata per rappresentare come oggetto Task<TResult> qualsiasi set arbitrario di operazioni. Le operazioni possono essere sincrone o asincrone e possono presentare vincoli di I/O, vincoli di calcolo o entrambi i tipi di vincolo.

Nell'esempio seguente viene mostrato come utilizzare un oggetto TaskCompletionSource<TResult> per esporre a codice client un set di operazioni WebClient asincrone come un oggetto Task di base. Il metodo consente di immettere una matrice di URL Web e un termine o un nome da ricercare, quindi restituisce il numero di volte che tale termine di ricerca viene trovato in ogni sito.

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

Per un esempio più completo che include una logica aggiuntiva di gestione delle eccezioni e che mostra come chiamare il metodo da codice client, vedere Procedura: eseguire il wrapping di modelli EAP in un'attività.

Tenere presente che qualsiasi attività creata da un oggetto TaskCompletionSource<TResult> verrà avviata da tale TaskCompletionSource e che pertanto il codice utente non deve chiamare il metodo Start su tale attività.

Implementazione del modello APM tramite attività

In alcuni scenari è possibile che sia opportuno esporre direttamente il modello IAsyncResult tramite l'utilizzo di coppie di metodi Begin/End in un'API. Ad esempio, è possibile che sia necessario conservare la coerenza con le API esistenti o che esistano strumenti automatizzati che richiedono questo modello. In tali casi è possibile utilizzare le attività per semplificare l'implementazione interna del modello APM.

Nell'esempio seguente viene mostrato come utilizzare le attività per implementare una coppia di metodi Begin/End per un metodo di lunga durata con vincoli di calcolo.

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

Utilizzo dell'esempio di codice StreamExtensions

Nel file Streamextensions.cs, disponibile in Esempi di programmazione in parallelo con .NET Framework 4 nel sito Web MSDN (la pagina potrebbe essere in inglese), sono contenute molte implementazioni di riferimento che utilizzano oggetti Task per l'I/O asincrono di file e di rete.

Vedere anche

Concetti

Task Parallel Library