Partekatu honen bidez:


Programación asincrónica tradicional de .NET y TPL

.NET proporciona los dos patrones estándar siguientes para realizar operaciones asincrónicas enlazadas a E/S y enlazadas a proceso:

La biblioteca paralela de tareas (TPL) se puede usar de varias maneras junto con cualquiera de los patrones asincrónicos. Puede exponer las operaciones de APM y EAP como Task objetos a los consumidores de bibliotecas, o puede exponer los patrones de APM, pero usar Task objetos para implementarlos internamente. En ambos escenarios, mediante el uso Task de objetos, puede simplificar el código y aprovechar las siguientes funcionalidades útiles:

  • Registre las devoluciones de llamada, en el formulario de continuaciones de la tarea, en cualquier momento después de que se haya iniciado la tarea.

  • Coordinar varias operaciones que se ejecutan en respuesta al método Begin_ mediante los métodos ContinueWhenAll y ContinueWhenAny, o los métodos WaitAll y WaitAny.

  • Encapsula las operaciones dependientes de E/S asincrónicas y de cálculo en un solo objeto Task.

  • Supervise el estado del Task objeto.

  • Gestiona el estado de una operación en el objeto Task usando TaskCompletionSource<TResult>.

Encapsulado de operaciones de APM en una tarea

Las clases System.Threading.Tasks.TaskFactory y System.Threading.Tasks.TaskFactory<TResult> proporcionan varias sobrecargas de los métodos TaskFactory.FromAsync y TaskFactory<TResult>.FromAsync que permiten encapsular un par de métodos begin/end de APM en una instancia Task o Task<TResult>. Las distintas sobrecargas admiten cualquier par de métodos begin/end que tengan de cero a tres parámetros de entrada.

Para los pares que tienen End métodos que devuelven un valor (un Function en Visual Basic), use los métodos de TaskFactory<TResult> que crean un Task<TResult>. Para los métodos End que devuelven un valor void (Sub en Visual Basic), use los métodos de TaskFactory que crean un objeto Task.

En aquellos pocos casos en los que el Begin método tiene más de tres parámetros o contiene ref o out parámetros, se proporcionan sobrecargas adicionales FromAsync que encapsulan solo el End método.

En el ejemplo siguiente, se muestra la signatura para la sobrecarga FromAsync que coincide con los métodos FileStream.BeginRead y FileStream.EndRead.

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

Esta sobrecarga toma tres parámetros de entrada, como se indica a continuación. El primer parámetro es un Func<T1,T2,T3,T4,T5,TResult> delegado que coincide con la firma del método FileStream.BeginRead. El segundo parámetro es un Func<T,TResult> delegado que toma un IAsyncResult y devuelve un TResult. Dado que EndRead devuelve un entero, el compilador deduce el tipo de TResult como Int32 y el tipo de la tarea como Task. Los cuatro últimos parámetros son idénticos a los del FileStream.BeginRead método :

  • Búfer en el que se van a almacenar los datos del archivo.

  • Desplazamiento en el búfer donde deben comenzar a escribirse los datos.

  • Cantidad máxima de datos que se van a leer del archivo.

  • Un objeto opcional que almacena los datos de estado definidos por el usuario que se van a pasar a la devolución de llamada.

Uso de ContinueWith para la funcionalidad de devolución de llamada

Si necesita acceso a los datos del archivo, en lugar del número de bytes, el FromAsync método no es suficiente. En su lugar, use Task, cuya Result propiedad contiene los datos del archivo. Para ello, agregue una continuación a la tarea original. La continuación realiza el trabajo que normalmente realizaría el delegado AsyncCallback. Se invoca cuando se completa el antecedente y se ha rellenado el búfer de datos. (El FileStream objeto debe cerrarse antes de devolver).

En el ejemplo siguiente se muestra cómo devolver un Task que encapsula el par BeginRead/ de la clase EndRead.

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

A continuación, se puede llamar al método , como se indica a continuación.


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

Proporcionar datos de estado personalizados

En las operaciones IAsyncResult típicas, si el delegado AsyncCallback requiere algún dato de estado personalizado, tiene que pasarlo a través del último parámetro Begin para que los datos se puedan empaquetar en el objeto IAsyncResult que se pasará finalmente al método de devolución de llamada. Normalmente, esto no es necesario cuando se usan los FromAsync métodos. Si los datos personalizados son conocidos para la continuación, se pueden capturar directamente en el delegado de continuación. El ejemplo siguiente se asemeja al ejemplo anterior, pero, en lugar de examinar la Result propiedad del antecedente, la continuación examina los datos de estado personalizados a los que puede acceder directamente el delegado de usuario de la continuación.

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);
        }
    });
}
Public Function GetFileStringAsync2(ByVal path As String) As Task(Of String)
    Dim fi = New FileInfo(path)
    Dim data(fi.Length - 1) 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

Sincronizar varias tareas de FromAsync

Los métodos estáticos ContinueWhenAll y ContinueWhenAny proporcionan flexibilidad adicional cuando se usan junto con los FromAsync métodos. En el ejemplo siguiente se muestra cómo iniciar varias operaciones de E/S asincrónicas y, a continuación, esperar a que se completen todas antes de ejecutar la continuación.

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();
    });
}
Public Function GetMultiFileData(ByVal filesToRead As String()) As Task(Of String)
    Dim fs As FileStream
    Dim tasks(filesToRead.Length - 1) 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

Tareas FromAsync solo para el método End

En los pocos casos en los que el método Begin necesita más de tres parámetros de entrada o tiene parámetros ref o out, puede usar las sobrecargas de FromAsync, por ejemplo, TaskFactory<TResult>.FromAsync(IAsyncResult, Func<IAsyncResult,TResult>), que representa solo el método End. Estos métodos también se pueden usar en cualquier escenario en el que te pasen un IAsyncResult y quieras encapsularlo en una tarea.

static Task<String> ReturnTaskFromAsyncResult()
{
    IAsyncResult ar = DoSomethingAsynchronously();
    Task<String> t = Task<string>.Factory.FromAsync(ar, _ =>
        {
            return (string)ar.AsyncState;
        });

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

Iniciar y cancelar tareas de FromAsync

La tarea devuelta por un FromAsync método tiene un estado de WaitingForActivation y la iniciará el sistema en algún momento después de crear la tarea. Si intenta llamar a Start en este tipo de tarea, se producirá una excepción.

No se puede cancelar una FromAsync tarea, ya que las APIs subyacentes de .NET no admiten actualmente la cancelación de operaciones de E/S de archivos o de red. Puede agregar la funcionalidad de cancelación a un método que encapsula una llamada FromAsync, pero sólo puede responder a la cancelación antes de que se llame a FromAsync o después de completar (por ejemplo, en una tarea de continuación).

Algunas clases que admiten EAP, por ejemplo, WebClient, admiten la cancelación y puede integrar esa funcionalidad de cancelación nativa mediante tokens de cancelación.

Exposición de operaciones de EAP complejas como tareas

El TPL no proporciona ningún método diseñado específicamente para encapsular una operación asincrónica basada en eventos de la misma manera que la FromAsync familia de métodos encapsula el IAsyncResult patrón. Sin embargo, el TPL proporciona la System.Threading.Tasks.TaskCompletionSource<TResult> clase , que se puede usar para representar cualquier conjunto arbitrario de operaciones como .Task<TResult> Las operaciones pueden ser sincrónicas o asincrónicas, y pueden estar enlazadas a E/S o enlazadas a proceso, o ambas.

En el ejemplo siguiente se muestra cómo utilizar un TaskCompletionSource<TResult> para exponer un conjunto de operaciones asincrónicas WebClient al código cliente como un Task<TResult> básico. El método permite escribir una matriz de direcciones URL web y un término o nombre para buscar y, a continuación, devuelve el número de veces que se produce el término de búsqueda en cada sitio.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

public class SimpleWebExample
{
  public 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.
              lock (m_lock)
              {
                 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.
                 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;
   }
}
Imports System.Collections.Generic
Imports System.Net
Imports System.Threading
Imports System.Threading.Tasks

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

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

        Dim webClients(urls.Length - 1) As WebClient

        ' 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 wc IsNot Nothing Then
                                   wc.CancelAsync()
                               End If
                           Next
                       End Sub)

        For i As Integer = 0 To urls.Length - 1
            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 args.Error IsNot 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.
            SyncLock (m_lock)
                results.Add(String.Format("{0} has {1} instances of {2}", args.UserState, nameCount, nameToSearch))
                count = count + 1
                If (count = addresses.Length) Then
                    tcs.TrySetResult(results.ToArray())
                End If
            End SyncLock
        End If
    End Sub
End Class

Para obtener un ejemplo más completo, que incluye el control de excepciones adicional y muestra cómo llamar al método desde el código de cliente, vea How to: Wrap EAP Patterns in a Task.

Recuerde que cualquier tarea creada por un TaskCompletionSource<TResult> se iniciará por ese TaskCompletionSource y, por lo tanto, el código de usuario no debe llamar al método Start en esa tarea.

Implementación del patrón de APM mediante tareas

En algunos escenarios, puede ser conveniente exponer directamente el IAsyncResult patrón mediante pares de métodos begin/end en una API. Por ejemplo, es posible que quiera mantener la coherencia con las API existentes o que tenga herramientas automatizadas que requieran este patrón. En tales casos, puede usar Task objetos para simplificar cómo se implementa el patrón de APM internamente.

En el ejemplo siguiente se muestra cómo usar las tareas para implementar un par de métodos begin/end de APM para un método enlazado al cálculo de ejecución prolongada.

class Calculator
{
    public IAsyncResult BeginCalculate(int decimalPlaces, AsyncCallback ac, object state)
    {
        Console.WriteLine($"Calling BeginCalculate on thread {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 {Thread.CurrentThread.ManagedThreadId}");

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

        // Actual implementation 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 {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 calculator 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 {Thread.CurrentThread.ManagedThreadId}; result = {piString}");
    }
}
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(antecedent) 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 implementation 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 calculator 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

Uso del código de ejemplo StreamExtensions

El archivo StreamExtensions.cs , en el repositorio de extras de extensiones paralelas de .NET Standard , contiene varias implementaciones de referencia que usan Task objetos para E/S de red y archivos asincrónicos.

Consulte también