TaskCompletionSource<TResult> 클래스

정의

대리자에 바인딩되지 않은 Task<TResult>의 생산자 측면을 나타내고 Task 속성을 통해 소비자 측면에 대한 액세스를 제공합니다.

generic <typename TResult>
public ref class TaskCompletionSource
public class TaskCompletionSource<TResult>
type TaskCompletionSource<'Result> = class
Public Class TaskCompletionSource(Of TResult)

형식 매개 변수

TResult

TaskCompletionSource<TResult>값과 연결된 결과 값의 형식입니다.

상속
TaskCompletionSource<TResult>

예제

다음 예제에서는 사용 하는 방법을 보여 줍니다는 TaskCompletionSource<TResult>:

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

class TCSDemo
{
    // Demonstrated features:
    // 		TaskCompletionSource ctor()
    // 		TaskCompletionSource.SetResult()
    // 		TaskCompletionSource.SetException()
    //		Task.Result
    // Expected results:
    // 		The attempt to get t1.Result blocks for ~1000ms until tcs1 gets signaled. 15 is printed out.
    // 		The attempt to get t2.Result blocks for ~1000ms until tcs2 gets signaled. An exception is printed out.
    static void Main()
    {
        TaskCompletionSource<int> tcs1 = new TaskCompletionSource<int>();
        Task<int> t1 = tcs1.Task;

        // Start a background task that will complete tcs1.Task
        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(1000);
            tcs1.SetResult(15);
        });

        // The attempt to get the result of t1 blocks the current thread until the completion source gets signaled.
        // It should be a wait of ~1000 ms.
        Stopwatch sw = Stopwatch.StartNew();
        int result = t1.Result;
        sw.Stop();

        Console.WriteLine("(ElapsedTime={0}): t1.Result={1} (expected 15) ", sw.ElapsedMilliseconds, result);

        // ------------------------------------------------------------------

        // Alternatively, an exception can be manually set on a TaskCompletionSource.Task
        TaskCompletionSource<int> tcs2 = new TaskCompletionSource<int>();
        Task<int> t2 = tcs2.Task;

        // Start a background Task that will complete tcs2.Task with an exception
        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(1000);
            tcs2.SetException(new InvalidOperationException("SIMULATED EXCEPTION"));
        });

        // The attempt to get the result of t2 blocks the current thread until the completion source gets signaled with either a result or an exception.
        // In either case it should be a wait of ~1000 ms.
        sw = Stopwatch.StartNew();
        try
        {
            result = t2.Result;

            Console.WriteLine("t2.Result succeeded. THIS WAS NOT EXPECTED.");
        }
        catch (AggregateException e)
        {
            Console.Write("(ElapsedTime={0}): ", sw.ElapsedMilliseconds);
            Console.WriteLine("The following exceptions have been thrown by t2.Result: (THIS WAS EXPECTED)");
            for (int j = 0; j < e.InnerExceptions.Count; j++)
            {
                Console.WriteLine("\n-------------------------------------------------\n{0}", e.InnerExceptions[j].ToString());
            }
        }
    }
}
Imports System.Diagnostics
Imports System.Threading
Imports System.Threading.Tasks

Module TCSDemo
    ' Demonstrated features:
    '   TaskCompletionSource ctor()
    '   TaskCompletionSource.SetResult()
    '   TaskCompletionSource.SetException()
    '   Task.Result
    ' Expected results:
    '   The attempt to get t1.Result blocks for ~1000ms until tcs1 gets signaled. 15 is printed out.
    '   The attempt to get t2.Result blocks for ~1000ms until tcs2 gets signaled. An exception is printed out.

    Private Sub Main()
        Dim tcs1 As New TaskCompletionSource(Of Integer)()
        Dim t1 As Task(Of Integer) = tcs1.Task

        ' Start a background task that will complete tcs1.Task
        Task.Factory.StartNew(Sub()
                                  Thread.Sleep(1000)
                                  tcs1.SetResult(15)
                              End Sub)

        ' The attempt to get the result of t1 blocks the current thread until the completion source gets signaled.
        ' It should be a wait of ~1000 ms.
        Dim sw As Stopwatch = Stopwatch.StartNew()
        Dim result As Integer = t1.Result
        sw.Stop()

        Console.WriteLine("(ElapsedTime={0}): t1.Result={1} (expected 15) ", sw.ElapsedMilliseconds, result)

        ' ------------------------------------------------------------------

        ' Alternatively, an exception can be manually set on a TaskCompletionSource.Task
        Dim tcs2 As New TaskCompletionSource(Of Integer)()
        Dim t2 As Task(Of Integer) = tcs2.Task

        ' Start a background Task that will complete tcs2.Task with an exception
        Task.Factory.StartNew(Sub()
                                  Thread.Sleep(1000)
                                  tcs2.SetException(New InvalidOperationException("SIMULATED EXCEPTION"))
                              End Sub)

        ' The attempt to get the result of t2 blocks the current thread until the completion source gets signaled with either a result or an exception.
        ' In either case it should be a wait of ~1000 ms.
        sw = Stopwatch.StartNew()
        Try
            result = t2.Result

            Console.WriteLine("t2.Result succeeded. THIS WAS NOT EXPECTED.")
        Catch e As AggregateException
            Console.Write("(ElapsedTime={0}): ", sw.ElapsedMilliseconds)
            Console.WriteLine("The following exceptions have been thrown by t2.Result: (THIS WAS EXPECTED)")
            For j As Integer = 0 To e.InnerExceptions.Count - 1
                Console.WriteLine(vbLf & "-------------------------------------------------" & vbLf & "{0}", e.InnerExceptions(j).ToString())
            Next
        End Try
    End Sub

End Module

설명

많은 시나리오에서 외부 비동기 작업을 나타낼 수 있도록 설정하는 Task<TResult> 것이 유용합니다. TaskCompletionSource<TResult> 이 목적을 위해 제공됩니다. 이를 통해 소비자에게 전달될 수 있는 작업을 만들 수 있습니다. 소비자는 태스크 멤버 변수를 처리하는 다른 시나리오와 동일한 방식으로 태스크의 멤버를 사용할 수 있습니다. 그러나 대부분의 태스크와 달리 TaskCompletionSource에서 만든 태스크의 상태는 TaskCompletionSource의 메서드에 의해 명시적으로 제어됩니다. 이렇게 하면 외부 비동기 작업의 완료를 기본 작업으로 전파할 수 있습니다. 또한 분리를 통해 소비자는 해당 TaskCompletionSource에 액세스하지 않고도 상태를 전환할 수 없습니다. 자세한 내용은 .NET 블로그를 사용한 병렬 프로그래밍에서 TaskCompletionSource<TResult>의 특성 항목을 참조하세요.

병렬 확장 샘플에는 사용 TaskCompletionSource<TResult>방법에 대한 예제도 포함되어 있습니다.

생성자

TaskCompletionSource<TResult>()

TaskCompletionSource<TResult>을 만듭니다.

TaskCompletionSource<TResult>(Object)

지정된 상태를 사용하여 TaskCompletionSource<TResult>을 만듭니다.

TaskCompletionSource<TResult>(Object, TaskCreationOptions)

지정된 상태 및 옵션을 사용하여 TaskCompletionSource<TResult>을 만듭니다.

TaskCompletionSource<TResult>(TaskCreationOptions)

지정된 옵션을 사용하여 TaskCompletionSource<TResult>을 만듭니다.

속성

Task

Task<TResult>에서 만든 TaskCompletionSource<TResult>를 가져옵니다.

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
SetCanceled()

내부 Task<TResult>Canceled 상태로 전환합니다.

SetCanceled(CancellationToken)

지정된 토큰을 사용하여 기본 Task<TResult>Canceled 상태로 전환합니다.

SetException(Exception)

내부 Task<TResult>Faulted 상태로 전환하고 지정된 예외에 바인딩합니다.

SetException(IEnumerable<Exception>)

내부 Task<TResult>Faulted 상태로 전환하고 예외 개체 컬렉션을 바인딩합니다.

SetResult(TResult)

내부 Task<TResult>RanToCompletion 상태로 전환합니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)
TrySetCanceled()

내부 Task<TResult>Canceled 상태로 전환하려고 시도합니다.

TrySetCanceled(CancellationToken)

내부 Task<TResult>Canceled 상태로 전환하려고 시도하고 취소 토큰을 취소된 작업에 저장할 수 있도록 합니다.

TrySetException(Exception)

내부 Task<TResult>Faulted 상태로 전환하고 지정된 예외에 바인딩하려고 합니다.

TrySetException(IEnumerable<Exception>)

내부 Task<TResult>Faulted 상태로 전환하고 예외 개체 컬렉션을 바인딩하려고 합니다.

TrySetResult(TResult)

내부 Task<TResult>RanToCompletion 상태로 전환하려고 시도합니다.

적용 대상

스레드 보안

모든 멤버 TaskCompletionSource<TResult> 는 스레드로부터 안전하며 여러 스레드에서 동시에 사용할 수 있습니다.

추가 정보