Aracılığıyla paylaş


TPL ve geleneksel .NET zaman uyumsuz programlama

.NET, G/Ç ile ilişkili ve işlemle ilişkili zaman uyumsuz işlemleri gerçekleştirmek için aşağıdaki iki standart deseni sağlar:

Görev Paralel Kitaplığı (TPL), zaman uyumsuz desenlerden biriyle birlikte çeşitli şekillerde kullanılabilir. Her iki APM ve EAP işlemlerini kitaplık tüketicilerine Task nesneleri olarak sunabilir veya APM desenlerini kullanıma sunarken, dahili olarak bunları Task nesneleriyle uygulayabilirsiniz. Her iki senaryoda da Task nesneleri kullanarak kodu basitleştirebilir ve aşağıdaki kullanışlı işlevlerden yararlanabilirsiniz:

  • Geri çağırmaları görev başlatıldıktan sonra istediğiniz zaman görev devamlılığı biçiminde kaydedin.

  • Begin_ ve ContinueWhenAll yöntemlerini veya ContinueWhenAny ve WaitAll yöntemlerini kullanarak bir WaitAny yöntemine yanıt olarak yürütülen birden çok işlemi koordine edin.

  • Aynı Task nesnesinde zaman uyumsuz G/Ç odaklı ve hesaplama odaklı işlemleri kapsülleyin.

  • Task nesnesinin durumunu izleyin.

  • Taskkullanarak bir işlemin durumunu bir TaskCompletionSource<TResult> nesnesine yönlendir.

APM operasyonlarını bir Görev içine sarmalama

Hem System.Threading.Tasks.TaskFactory hem de System.Threading.Tasks.TaskFactory<TResult> sınıfları, bir TaskFactory.FromAsync veya TaskFactory<TResult>.FromAsync örnekte APM başlangıç/bitiş yöntemi çiftini kapsüllemenize olanak sağlayan Task ve Task<TResult> yöntemlerinin çeşitli aşırı yüklemelerini sağlar. Çeşitli aşırı yüklemeler, sıfırdan üçe kadar giriş parametresi olan herhangi bir başlangıç/bitiş yöntemi çiftini barındırmaktadır.

Bir değer döndüren End yöntemleri olan çiftler için (Visual Basic'te Function), TaskFactory<TResult>oluşturan Task<TResult> yöntemlerini kullanın. void döndüren End yöntemler için (Visual Basic'te bir Sub), TaskFactory içinde Taskoluşturan yöntemleri kullanın.

Begin yönteminin üçten fazla parametreye sahip olduğu veya ref veya out parametreleri içerdiği bu birkaç durumda, yalnızca FromAsync yöntemini kapsülleyen ek End aşırı yüklemeleri sağlanır.

Aşağıdaki örnek, FromAsync ve FileStream.BeginRead yöntemleriyle eşleşen FileStream.EndRead aşırı yüklemesinin imzasını gösterir.

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)

Bu aşırı yükleme aşağıdaki gibi üç giriş parametresi alır. İlk parametre, Func<T1,T2,T3,T4,T5,TResult> delegesi olup FileStream.BeginRead yönteminin imzasıyla eşleşir. İkinci parametre, Func<T,TResult> alan ve IAsyncResultdöndüren bir TResult temsilcisidir. EndRead bir tamsayı döndürdüğünden, derleyici TResult türünü Int32 ve görevin türünü Taskolarak çıkarsar. Son dört parametre, FileStream.BeginRead yöntemindekilerle aynıdır:

  • Dosya verilerinin depolandığı arabellek.

  • Veri yazmaya başlamak için arabellekteki uzaklık.

  • Dosyadan okunacak en fazla veri miktarı.

  • Geri çağırmaya geçirebilmek için kullanıcı tanımlı durum verilerini depolayan isteğe bağlı bir nesne.

Geri çağırma işlevi için ContinueWith kullanma

Dosyadaki verilere yalnızca bayt sayısının aksine erişmeniz gerekiyorsa, FromAsync yöntemi yeterli değildir. Bunun yerine, dosya verilerini içeren Task özelliğine sahip Resultkullanın. Bunu, özgün göreve bir devamlılık ekleyerek yapabilirsiniz. Devam, genellikle AsyncCallback temsilcisi tarafından gerçekleştirilecek işi gerçekleştirir. Öncül tamamlandığında ve veri arabelleği doldurulduğunda çağrılır. (FileStream nesnesi geri dönmeden önce kapatılmalıdır.)

Aşağıdaki örnekte, Task sınıfının BeginRead/EndRead çiftini kapsülleyen bir FileStream nasıl döndürüleceği gösterilmektedir.

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

Yöntem daha sonra aşağıdaki gibi çağrılabilir.


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

Özel durum verileri sağlama

Tipik IAsyncResult işlemlerinde, AsyncCallback temsilciniz bazı özel durum verileri gerektiriyorsa, verilerin sonunda geri çağırma yöntemine geçirilen Begin nesnesine paketlenebilmesi için bunu IAsyncResult yöntemindeki son parametreden geçirmeniz gerekir. bu genellikle FromAsync yöntemleri kullanıldığında gerekli değildir. Özel veriler devam temsilcisi tarafından biliniyorsa, doğrudan devam temsilcisinde yakalanabilir. Aşağıdaki örnek önceki örneğe benzer, ancak öncül öğesinin Result özelliğini incelemek yerine, devamlılık kullanıcı temsilcisi tarafından doğrudan erişilebilen özel durum verilerini inceler.

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

Birden çok FromAsync görevini eşitleme

Statik ContinueWhenAll ve ContinueWhenAny yöntemleri, FromAsync yöntemleriyle birlikte kullanıldığında daha fazla esneklik sağlar. Aşağıdaki örnek, birden çok zaman uyumsuz giriş/çıkış işleminin nasıl başlatılacağını ve ardından devamını yürütmeden önce hepsinin tamamlanmasını nasıl beklemeniz gerektiğini göstermektedir.

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

Yalnızca End yöntemi için FromAsync görevleri

Begin yönteminin üçten fazla giriş parametresi gerektirdiği veya ref veya out parametreleri olduğu birkaç durumda, yalnızca FromAsync yöntemini temsil eden TaskFactory<TResult>.FromAsync(IAsyncResult, Func<IAsyncResult,TResult>)gibi End aşırı yüklemelerini kullanabilirsiniz. Bu yöntemler, size bir IAsyncResult geçirildiğinde ve bunu Görev içinde kapsüllemek istediğiniz her türlü senaryoda kullanılabilir.

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

FromAsync görevlerini başlatma ve iptal etme

Bir FromAsync yöntemi tarafından döndürülen görevin durumu WaitingForActivation'dir ve görev oluşturulduktan sonra bir noktada sistem tarafından başlatılacaktır. Böyle bir görev üzerinde Başlat komutunu çalıştırmaya çalışırsanız, bir istisna oluşur.

Temel alınan .NET API'leri şu anda dosya veya ağ G/Ç'sinin devam eden iptalini desteklemediğinden, FromAsync görevi iptal edemezsiniz. bir FromAsync çağrısını kapsülleyen bir yönteme iptal işlevi ekleyebilirsiniz, ancak iptali yalnızca FromAsync çağrılmadan veya tamamlandıktan sonra yanıtlayabilirsiniz (örneğin, bir devamlılık görevinde).

WebClientgibi EAP'yi destekleyen bazı sınıflar iptali destekler ve iptal belirteçlerini kullanarak bu yerel iptal işlevini tümleştirebilirsiniz.

Karmaşık EAP işlemlerini görev olarak sunma

TPL, FromAsync yöntem ailesinin IAsyncResult desenini sardığı gibi olay tabanlı bir eş zamanlı olmayan işlemi kapsüllemek için özel olarak tasarlanmış herhangi bir yöntem sağlamaz. Ancak, TPL System.Threading.Tasks.TaskCompletionSource<TResult> sınıfını sağlar. Bu sınıf, herhangi bir rastgele işlem kümesini Task<TResult>olarak temsil etmek için kullanılabilir. İşlemler senkron veya asenkron olabilir ve G/Ç sınırlı veya işlem sınırlı ya da her ikisi de olabilir.

Aşağıdaki örnekte, istemci kodunda temel bir TaskCompletionSource<TResult>olarak zaman uyumsuz WebClient işlemleri kümesini kullanıma açmak için bir Task<TResult> nasıl kullanılacağı gösterilmektedir. yöntemi, bir Web URL'leri dizisi ve aranacak bir terim veya ad girmenize olanak tanır ve her sitede arama teriminin kaç kez gerçekleştiğini döndürür.

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

Ek özel durum işleme içeren ve istemci kodundan yöntemini çağırmayı gösteren daha eksiksiz bir örnek için bkz. Nasıl yapılır: GörevEAP Desenlerini Sarmalama.

Bir TaskCompletionSource<TResult> tarafından oluşturulan herhangi bir görevin bu TaskCompletionSource tarafından başlatılacağını ve bu nedenle kullanıcı kodunun bu görevde Start yöntemini çağırmaması gerektiğini unutmayın.

Görevleri kullanarak APM desenini uygulama

Bazı senaryolarda, bir API'de begin/end yöntem çiftlerini kullanarak IAsyncResult düzenini doğrudan kullanıma sunma tercih edilebilir. Örneğin, mevcut API'lerle tutarlılığı korumak isteyebilir veya bu düzeni gerektiren otomatik araçlara sahip olabilirsiniz. Böyle durumlarda, APM deseninin dahili olarak nasıl uygulandığını basitleştirmek için Task nesneleri kullanabilirsiniz.

Aşağıdaki örnek, uzun süre çalışan bir hesaplama kaynaklı metot için bir APM başlangıç/bitiş metot çifti uygulamak amacıyla görevlerin nasıl kullanılacağını göstermektedir.

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

StreamExtensions örnek kodunu kullanma

.NET Standard paralel uzantı ekleri deposundaki StreamExtensions.cs dosyası, zaman uyumsuz dosya ve ağ G/Ç için Task nesneleri kullanan çeşitli başvuru uygulamaları içerir.

Ayrıca bkz.