TPL 및 일반적인 .NET 비동기 프로그래밍

.NET에서는 I/O에 바인딩된 비동기 작업과 컴퓨팅에 바인딩된 비동기 작업을 수행하도록 다음 표준 패턴 두 개를 제공합니다.

TPL(작업 병렬 라이브러리)을 비동기 패턴의 하나와 함께 다양한 방법으로 사용할 수 있습니다. APM 및 EAP 작업을 둘 다 라이브러리 소비자에 대한 Task 개체로 공개하거나, APM 패턴을 공개하지만 Task 개체를 사용하여 내부적으로 구현할 수 있습니다. 두 시나리오에서 모두 Task 개체를 사용하여 코드를 간소화하고 다음 유용한 기능을 활용할 수 있습니다.

  • 작업이 시작되고 나서 언제든지 작업 연속 형태로 콜백을 등록합니다.

  • ContinueWhenAllContinueWhenAny 메서드를 사용하거나 WaitAllWaitAny 메서드를 사용하여 Begin_ 메서드에 대한 응답으로 실행되는 여러 작업을 조정합니다.

  • I/O에 바인딩된 비동기 작업과 컴퓨팅에 바인딩된 비동기 작업을 같은 Task 개체로 캡슐화합니다.

  • Task 개체 상태를 모니터링합니다.

  • TaskCompletionSource<TResult>을 사용하여 작업 상태를 Task 개체에 마샬링합니다.

작업으로 APM 작업 래핑

System.Threading.Tasks.TaskFactorySystem.Threading.Tasks.TaskFactory<TResult> 클래스는 둘 다 APM begin/end 메서드 쌍을 Task 또는 Task<TResult> 인스턴스 하나로 캡슐화하도록 하는 TaskFactory.FromAsyncTaskFactory<TResult>.FromAsync 메서드의 여러 가지 오버로드를 제공합니다. 다양한 오버로드가 입력 매개 변수 수가 0~3개인 begin/end 메서드 쌍을 수용합니다.

값(Visual Basic의 Function)을 반환하는 End 메서드가 있는 쌍의 경우 TaskFactory<TResult>에서 Task<TResult>을 만드는 메서드를 사용합니다. void(Visual Basic의 Sub)를 반환하는 End 메서드의 경우 TaskFactory에서 Task를 만드는 메서드를 사용합니다.

Begin 메서드에 매개 변수가 4개 이상 포함되거나 ref 또는 out 매개 변수가 포함되는 경우에는 End 메서드만 캡슐화하는 추가 FromAsync 오버로드가 제공됩니다.

다음 예제에서는 FileStream.BeginReadFileStream.EndRead 메서드와 일치하는 FromAsync 오버로드에 대한 서명을 보여 줍니다.

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)

이 오버로드는 다음과 같이 입력 매개 변수 세 개를 사용합니다. 첫 번째 매개 변수는 FileStream.BeginRead 메서드의 서명과 일치하는 Func<T1,T2,T3,T4,T5,TResult> 대리자입니다. 두 번째 매개 변수는 IAsyncResult를 사용하고 TResult를 반환하는 Func<T,TResult> 대리자입니다. EndRead는 정수를 반환하므로 컴파일러에서는 TResult 형식을 Int32로 유추하고 작업 형식을 Task로 유추합니다. 마지막 매개 변수 4개는 FileStream.BeginRead 메서드의 매개 변수와 동일합니다.

  • 파일 데이터를 저장할 버퍼입니다.

  • 데이터 쓰기를 시작할 버퍼의 오프셋입니다.

  • 파일에서 읽을 최대 데이터 양입니다.

  • 콜백에 전달할 사용자 정의 상태 데이터를 저장하는 선택적 개체입니다.

콜백 기능에 ContinueWith 사용

단순한 바이트 수와는 달리 파일의 데이터에 대한 액세스 권한이 필요할 경우에는 FromAsync 메서드로는 충분하지 않습니다. 대신에 파일 데이터가 들어 있는 Result 속성이 포함된 Task를 사용하세요. 이 작업을 하려면 원래 작업에 연속을 추가합니다. 연속은 일반적으로 AsyncCallback 대리자에서 수행하는 작업을 수행합니다. 연속은 선행이 완료되고 데이터 버퍼가 채워졌을 때 호출됩니다. 돌아가기 전에 FileStream 개체를 닫아야 합니다.

다음 예제에서는 FileStream 클래스의 BeginRead/EndRead 쌍을 캡슐화하는 Task를 반환하는 방법을 보여 줍니다.

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

그리고 나서 다음과 같이 메서드를 호출할 수 있습니다.


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

사용자 지정 상태 데이터 제공

일반적인 IAsyncResult 작업에서 AsyncCallback 대리자에 사용자 지정 상태 데이터가 필요하면 Begin 메서드의 마지막 매개 변수를 통해 데이터를 전달해야 하므로, 데이터를 IAsyncResult 개체로 데이터를 패키지하고 나서 최종적으로 콜백 메서드에 전달할 수 있습니다. 일반적으로 FromAsync 메서드를 사용할 때 이 기능이 필요합니다. 사용자 지정 데이터가 연속에 알려지면 연속 대리자에서 직접 캡슐화될 수 있습니다. 다음 예제는 이전 예제와 비슷하지만 선행의 Result 속성을 검사하지 않고 연속의 사용자 대리자에 직접 액세스할 수 있는 사용자 지정 상태 데이터를 연속에서 검사합니다.

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

여러 FromAsync 작업 동기화

정적 ContinueWhenAllContinueWhenAny 메서드는 FromAsync 메서드와 함께 사용될 때 더 큰 유연성을 제공합니다. 다음 예제에서는 여러 비동기 I/O 작업을 시작하고 연속을 실행하기 전에 모든 작업이 완료될 때까지 기다리는 방법을 보여 줍니다.

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

End 메서드 전용 FromAsync 작업

Begin 메서드에 입력 매개 변수가 4개 이상 필요하거나 ref 또는 out 매개 변수가 있는 경우 End 메서드만 표현하는 FromAsync 오버로드(예: TaskFactory<TResult>.FromAsync(IAsyncResult, Func<IAsyncResult,TResult>))를 사용할 수 있습니다. IAsyncResult를 전달하고 이를 작업으로 캡슐화하려는 시나리오에서 관련 메서드를 사용할 수도 있습니다.

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 작업 시작 및 취소

FromAsync 메서드에서 반환된 작업은 WaitingForActivation 상태이고 만들어진 후 일정 시점에 시스템에 의해 시작됩니다. 해당 작업에서 시작을 호출하려고 하면 예외가 발생합니다.

기본 .NET API에서는 현재 파일 또는 네트워크 I/O의 진행 중 취소를 지원하지 않으므로 FromAsync 작업을 취소할 수 없습니다. FromAsync 호출을 캡슐화하는 메서드에 취소 기능을 추가할 수 있지만, FromAsync가 호출되기 전이나 완료된 후(예: 연속 작업에서)에만 취소에 응답할 수 있습니다.

WebClient와 같이 EAP를 지원하는 몇몇 클래스는 취소를 지원하며 취소 토큰을 사용하여 해당 네이티브 취소 기능을 통합할 수 있습니다.

복잡한 EAP 작업을 작업으로 공개

TPL은 메서드의 FromAsync 패밀리가 IAsyncResult 패턴을 래핑하는 것과 같은 방법으로 이벤트 기반 비동기 작업을 캡슐화하도록 특수 디자인된 메서드를 제공하지 않습니다. 그러나 TPL은 임의 작업 집합을 Task<TResult>로 표현하는 데 사용할 수 있는 System.Threading.Tasks.TaskCompletionSource<TResult> 클래스를 제공합니다. 작업은 동기 또는 비동기 작업일 수 있고 I/O에 바인딩되거나 컴퓨팅에 바인딩된 작업이거나 두 작업에 모두 해당할 수 있습니다.

다음 예제에서는 a TaskCompletionSource<TResult>을 사용하여 비동기 WebClient 작업 집합을 클라이언트 코드에 기본 Task<TResult>로 노출하는 방법을 보여 줍니다. 메서드를 통해 웹 URL 배열과 검색할 용어 또는 이름을 입력할 수 있고, 그리고 나서 각 사이트에서 검색 용어가 발생하는 횟수가 반환됩니다.

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

추가적인 예외 처리가 포함되고 클라이언트 코드에서 메서드를 호출하는 방법을 보여주는 더 자세한 예제는 방법: EAP 패턴을 작업으로 래핑을 참조하세요.

TaskCompletionSource<TResult>에서 만든 작업은 TaskCompletionSource에 의해 시작되므로 사용자 코드는 해당 작업에서 Start 메서드를 호출하면 안 됩니다.

작업을 사용하여 APM 패턴 구현

몇몇 시나리오에서는 API에서 begin/end 메서드 쌍을 사용하여 IAsyncResult 패턴을 직접 공개하는 것이 좋을 수 있습니다. 예를 들어 기존 API와 일관성을 유지하려고 하거나 이 패턴이 필요한 자동화된 도구가 있을 수 있습니다. 이 경우 Task 개체를 사용하여 APM 패턴을 내부적으로 구현하는 방법을 간소화할 수 있습니다.

다음 예제에서는 작업을 사용하여 컴퓨팅에 바인딩된 장기 실행 메서드에 대한 APM begin/end 메서드 쌍을 구현하는 방법을 보여 줍니다.

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 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 {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 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 {0}; result = {1}",
                    Thread.CurrentThread.ManagedThreadId, 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 샘플 코드 사용

.NET Standard 병렬 확장 추가 항목에서 StreamExtensions.cs 파일에는 비동기 파일 및 네트워크 I/O에 대한 Task 개체를 사용하는 몇 가지 참조 구현이 포함되어 있습니다.

참고 항목