다음을 통해 공유


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

.NET Framework에서는 I/O 바인딩된 비동기 작업과 CPU 바인딩된 비동기 작업을 수행하기 위한 다음 두 가지의 표준 패턴을 제공합니다.

TPL(작업 병렬 라이브러리)은 비동기 패턴 중 하나와 함께 다양한 방법으로 사용할 수 있습니다. APM 및 EAP 작업을 라이브러리 소비자에게 Task 개체로 노출하거나, APM 패턴을 노출하되 Task 개체를 사용하여 이를 내부적으로 구현할 수 있습니다. 두 경우 모두 Task 개체를 사용하면 코드를 단순화하고 다음과 같은 유용한 기능을 활용할 수 있습니다.

  • 작업이 시작된 후 언제든지 작업 연속의 형태로 콜백을 등록할 수 있습니다.

  • ContinueWhenAll 또는 ContinueWhenAny 메서드나 WaitAll 또는 WaitAny 메서드를 사용하여 Begin_ 메서드에 대한 응답으로 실행되는 여러 작업을 조정할 수 있습니다.

  • I/O 바인딩된 비동기 작업과 CPU 바인딩된 비동기 작업을 동일한 Task 개체에 캡슐화할 수 있습니다.

  • Task 개체의 상태를 모니터링할 수 있습니다.

  • TaskCompletionSource<TResult>를 사용하여 작업 상태를 Task 개체로 마샬링할 수 있습니다.

Task에 APM 작업 래핑

System.Threading.Tasks.TaskFactorySystem.Threading.Tasks.TaskFactory<TResult> 클래스는 모두 APM Begin/End 메서드 쌍을 하나의 Task 인스턴스 또는 Task<TResult> 인스턴스에 캡슐화할 수 있게 해 주는 FromAsyncFromAsync 메서드의 여러 오버로드를 제공합니다. 이러한 다양한 오버로드는 0개부터 세 개까지의 입력 매개 변수를 사용하는 Begin/End 메서드 쌍을 수용합니다.

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

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

다음 코드 예제에서는 FileStream.BeginReadFileStream.EndRead 메서드와 일치하는 FromAsync 오버로드의 시그니처를 보여 줍니다. 이 오버로드는 다음과 같이 세 개의 입력 매개 변수를 사용합니다.

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
    ) 

첫 번째 매개 변수는 FileStream.BeginRead 메서드의 시그니처와 일치하는 Func<T1, T2, T3, T4, T5, TResult> 대리자입니다. 두 번째 매개 변수는 IAsyncResult를 사용하고 TResult를 반환하는 Func<T, TResult> 대리자입니다. EndRead는 정수를 반환하므로 컴파일러에서는 TResult의 형식과 작업의 형식을 각각 Int32와 Task<Int32>로 유추합니다. 마지막 네 개의 매개 변수는 FileStream.BeginRead 메서드의 매개 변수와 일치하며 다음을 나타냅니다.

  • 파일 데이터를 저장할 버퍼

  • 버퍼에서 데이터 쓰기를 시작할 위치의 오프셋

  • 파일에서 읽을 데이터의 최대 양

  • 콜백에 전달할 사용자 정의 상태 데이터가 저장되는 선택적 개체

콜백 기능에 ContinueWith 사용

파일의 바이트 수에만 액세스할 때와 달리 파일의 데이터에 액세스해야 하는 경우에는 FromAsync 메서드로 충분하지 않습니다. 이 경우에는 파일 데이터가 포함되는 Result 속성을 갖는 Task<String>를 사용합니다. 이렇게 하려면 원래 작업에 연속 작업을 추가합니다. 연속 작업은 일반적으로 AsyncCallback 대리자에 의해 수행되는 작업을 수행합니다. 연속 작업은 선행 작업이 완료되고 데이터 버퍼가 채워졌을 때 호출됩니다. 또한 반환되기 전에 FileStream 개체가 닫혀야 합니다.

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

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

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

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

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

일반적인 IAsyncResult 작업에서 AsyncCallback 대리자에 사용자 지정 상태 데이터를 사용해야 하는 경우, Begin 메서드의 마지막 매개 변수에 이 데이터를 전달하여 최종적으로 콜백 메서드에 전달되는 IAsyncResult 개체에 이 데이터가 패키지될 수 있도록 해야 합니다. 일반적으로 FromAsync 메서드가 사용될 경우에는 이 데이터가 필요하지 않습니다. 연속 작업에 사용자 지정 데이터가 알려진 경우 연속 작업 대리자에서 직접 해당 데이터를 캡처할 수 있습니다. 다음 예제는 앞의 예제와 유사하지만 연속 작업에서 선행 작업의 Result 속성 대신 연속 작업의 사용자 대리자가 직접 액세스할 수 있는 사용자 지정 상태 데이터를 확인합니다.

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

}

여러 FromAsync 작업 동기화

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

Public Function GetMultiFileData(ByVal filesToRead As String()) As Task(Of String)
    Dim fs As FileStream
    Dim tasks(filesToRead.Length) As Task(Of String)
    Dim fileData() As Byte = Nothing
    For i As Integer = 0 To filesToRead.Length
        fileData(&H1000) = New Byte()
        fs = New FileStream(filesToRead(i), FileMode.Open, FileAccess.Read, FileShare.Read, fileData.Length, True)

        ' By adding the continuation here, the 
        ' Result of each task will be a string.
        tasks(i) = Task(Of Integer).Factory.FromAsync(AddressOf fs.BeginRead,
                                                      AddressOf fs.EndRead,
                                                      fileData,
                                                      0,
                                                      fileData.Length,
                                                      Nothing).
                                                  ContinueWith(Function(antecedent)
                                                                   fs.Close()
                                                                   'If we did not receive the entire file, the end of the
                                                                   ' data buffer will contain garbage.
                                                                   If (antecedent.Result < fileData.Length) Then
                                                                       ReDim Preserve fileData(antecedent.Result)
                                                                   End If

                                                                   'Will be returned in the Result property of the Task<string>
                                                                   ' at some future point after the asynchronous file I/O operation completes.
                                                                   Return New UTF8Encoding().GetString(fileData)
                                                               End Function)
    Next

    Return Task(Of String).Factory.ContinueWhenAll(tasks, Function(data)

                                                              ' Propagate all exceptions and mark all faulted tasks as observed.
                                                              Task.WaitAll(data)

                                                              ' Combine the results from all tasks.
                                                              Dim sb As New StringBuilder()
                                                              For Each t As Task(Of String) In data
                                                                  sb.Append(t.Result)
                                                              Next
                                                              ' Final result to be returned eventually on the calling thread.
                                                              Return sb.ToString()
                                                          End Function)
End Function
public Task<string> GetMultiFileData(string[] filesToRead)
{
    FileStream fs;
    Task<string>[] tasks = new Task<string>[filesToRead.Length];
    byte[] fileData = null;
    for (int i = 0; i < filesToRead.Length; i++)
    {
        fileData = new byte[0x1000];
        fs = new FileStream(filesToRead[i], FileMode.Open, FileAccess.Read, FileShare.Read, fileData.Length, true);

        // By adding the continuation here, the 
        // Result of each task will be a string.
        tasks[i] = Task<int>.Factory.FromAsync(
                 fs.BeginRead, fs.EndRead, fileData, 0, fileData.Length, null)
                 .ContinueWith((antecedent) =>
                     {
                         fs.Close();

                         // If we did not receive the entire file, the end of the
                         // data buffer will contain garbage.
                         if (antecedent.Result < fileData.Length)
                             Array.Resize(ref fileData, antecedent.Result);

                         // Will be returned in the Result property of the Task<string>
                         // at some future point after the asynchronous file I/O operation completes.
                         return new UTF8Encoding().GetString(fileData);
                     });
    }

    // Wait for all tasks to complete. 
    return Task<string>.Factory.ContinueWhenAll(tasks, (data) =>
    {
        // Propagate all exceptions and mark all faulted tasks as observed.
        Task.WaitAll(data);

        // Combine the results from all tasks.
        StringBuilder sb = new StringBuilder();
        foreach (var t in data)
        {
            sb.Append(t.Result);
        }
        // Final result to be returned eventually on the calling thread.
        return sb.ToString();
    });

}

End 메서드 전용 FromAsync 작업

Begin 메서드에 네 개 이상의 입력 매개 변수가 필요하거나 ref 또는 out 매개 변수가 포함된 일부 경우, End 메서드만 나타내는 TaskFactory<TResult>.FromAsync(IAsyncResult, Func<IAsyncResult, TResult>)와 같은 FromAsync 오버로드를 사용할 수 있습니다. IAsyncResult를 전달받아 이를 Task에 캡슐화하려는 경우에도 이러한 메서드를 사용할 수 있습니다.

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

FromAsync 작업 시작 및 취소

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

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

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

복잡한 EAP 작업을 Task로 노출

TPL에서는 메서드의 FromAsync 패밀리가 IAsyncResult 패턴을 래핑하는 것과 동일한 방법으로 이벤트 기반 비동기 작업을 캡슐화하기 위한 특별한 메서드가 제공되지 않습니다. 그러나 TPL에서는 임의의 작업 집합을 Task<TResult>로 나타내는 데 사용할 수 있는 System.Threading.Tasks.TaskCompletionSource<TResult> 클래스가 제공됩니다. 이러한 작업은 동기 또는 비동기 작업일 수 있으며 I/O 바인딩된 작업, CPU 바인딩된 작업 또는 둘 모두일 수 있습니다.

다음 예제에서는 TaskCompletionSource<TResult>를 사용하여 일련의 비동기 WebClient 작업을 클라이언트 코드에 기본 Task로 노출하는 방법을 보여 줍니다. 이 방법을 사용하면 웹 URL의 배열과 검색할 용어 또는 이름을 입력한 다음 각 사이트에서 해당 검색어가 나타나는 횟수를 반환할 수 있습니다.

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

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

TaskCompletionSource<TResult>에 의해 만들어진 작업은 해당 TaskCompletionSource에 의해 시작되므로 사용자 코드에서 해당 작업에 대한 Start 메서드를 호출하지 말아야 합니다.

Task를 사용하여 APM 패턴 구현

일부 경우에는 API에 Begin/End 메서드 쌍을 사용하여 IAsyncResult 패턴을 직접 노출하는 것이 좋을 수 있습니다. 예를 들어 기존 API와의 일관성을 유지하려는 경우나 이 패턴이 필요한 자동화된 도구가 있는 경우가 이에 해당합니다. 이러한 경우 Task를 사용하여 APM 패턴이 내부적으로 구현되는 방식을 단순화할 수 있습니다.

다음 예제에서는 Task를 사용하여 CPU 바인딩된 장기 실행 메서드의 APM Begin/End 메서드 쌍을 구현하는 방법을 보여 줍니다.

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

StreamExtensions 샘플 코드 사용

MSDN 웹 사이트의 Samples for Parallel Programming with the .NET Framework 4에서 제공되는 Streamextensions.cs 파일에는 비동기 파일 및 네트워크 I/O에 Task 개체를 사용하는 몇 가지 참조 구현이 들어 있습니다.

참고 항목

개념

작업 병렬 라이브러리