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 블로그가 있는 병렬 프로그래밍의 항목 <TResult> 항목을 참조하세요.

생성자

Name Description
TaskCompletionSource<TResult>()

TaskCompletionSource<TResult> 항목을 만듭니다.

TaskCompletionSource<TResult>(Object, TaskCreationOptions)

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

TaskCompletionSource<TResult>(Object)

TaskCompletionSource<TResult> 지정된 상태로 만듭니다.

TaskCompletionSource<TResult>(TaskCreationOptions)

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

속성

Name Description
Task

이 메서드에서 만든 값을 Task<TResult>TaskCompletionSource<TResult>가져옵니다.

메서드

Name Description
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 를 상태로 전환하고 예외 개체 컬렉션을 바인딩합니다.

SetFromTask(Task<TResult>)

기본 Task<TResult> 을 지정된 완료 상태와 동일한 완료 상태로 전환합니다 completedTask.

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 을 상태로 전환하려고 시도하고 예외 개체의 컬렉션을 바인딩합니다.

TrySetFromTask(Task<TResult>)

기본 Task<TResult> 을 지정된 완료 상태와 동일한 완료 상태로 전환하려고 시도합니다 completedTask.

TrySetResult(TResult)

기본을 상태로 전환하려고 시도합니다 Task<TResult>RanToCompletion .

적용 대상

스레드 보안

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

추가 정보