TaskCompletionSource<TResult> 클래스

정의

대리자에 바인딩되지 않은 Task<TResult>의 생산자 측면을 나타내고 Task 속성을 통해 소비자 측면에 대한 액세스를 제공합니다.Represents the producer side of a Task<TResult> unbound to a delegate, providing access to the consumer side through the Task property.

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

형식 매개 변수

TResult

TaskCompletionSource<TResult>와 연결 된 결과 값의 형식-0입니다.The type of the result value associated with this TaskCompletionSource<TResult>.

상속
TaskCompletionSource<TResult>

예제

다음 예제에서는 사용 하는 방법을 보여 줍니다는 TaskCompletionSource<TResult>:The following example shows how to use a 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> 외부 비동기 작업을 나타내는입니다.In many scenarios, it is useful to enable a Task<TResult> to represent an external asynchronous operation. TaskCompletionSource<TResult> 이 목적을 위해 제공 됩니다.TaskCompletionSource<TResult> is provided for this purpose. 소비자에 게 전달할 수 있는 작업을 만들을 수 있습니다.It enables the creation of a task that can be handed out to consumers. 소비자가 멤버를 사용할 수 작업의 동일한 방식으로 작업 멤버 변수를 처리 하는 다른 모든 시나리오에서 일관 되 게 합니다.The consumers can use the members of the task the same way as they would in any other scenario handling task member variables. 그러나 대부분의 작업을 달리를 TaskCompletionSource로 만든 작업의 상태 제어 됩니다 명시적으로 TaskCompletionSource의 메서드에 의해.However, unlike most tasks, the state of a task created by a TaskCompletionSource is controlled explicitly by the methods on TaskCompletionSource. 이 통해 기본 작업에 전파 외부 비동기 작업을 완료 합니다.This enables the completion of the external asynchronous operation to be propagated to the underlying Task. 분리도 되도록 소비자 하지 해당 TaskCompletionSource에 액세스할 수 없는 상태를 전환할 수 있습니다.The separation also ensures that consumers are not able to transition the state without access to the corresponding TaskCompletionSource. 자세한 내용은 항목을 참조 하세요. The 특성 TaskCompletionSource<TResult > 에서 Parallel Programming with.NET 블로그.For more information, see the entry The Nature of TaskCompletionSource<TResult> in the Parallel Programming with .NET blog.

합니다 Parallel Extensions samples 도 사용 하는 방법의 예가 포함 되어 TaskCompletionSource<TResult>입니다.The Parallel Extensions samples also contain examples of how to use TaskCompletionSource<TResult>.

생성자

TaskCompletionSource<TResult>()

TaskCompletionSource<TResult>을 만듭니다.Creates a TaskCompletionSource<TResult>.

TaskCompletionSource<TResult>(Object)

지정된 상태를 사용하여 TaskCompletionSource<TResult>을 만듭니다.Creates a TaskCompletionSource<TResult> with the specified state.

TaskCompletionSource<TResult>(Object, TaskCreationOptions)

지정된 상태 및 옵션을 사용하여 TaskCompletionSource<TResult>을 만듭니다.Creates a TaskCompletionSource<TResult> with the specified state and options.

TaskCompletionSource<TResult>(TaskCreationOptions)

지정된 옵션을 사용하여 TaskCompletionSource<TResult>을 만듭니다.Creates a TaskCompletionSource<TResult> with the specified options.

속성

Task

Task<TResult>에서 만든 TaskCompletionSource<TResult>를 가져옵니다.Gets the Task<TResult> created by this TaskCompletionSource<TResult>.

메서드

Equals(Object)

지정한 개체와 현재 개체가 같은지 여부를 확인합니다.Determines whether the specified object is equal to the current object.

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

기본 해시 함수로 작동합니다.Serves as the default hash function.

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

현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance.

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

현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object.

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

내부 Task<TResult>Canceled 상태로 전환합니다.Transitions the underlying Task<TResult> into the Canceled state.

SetException(Exception)

내부 Task<TResult>Faulted 상태로 전환하고 지정된 예외에 바인딩합니다.Transitions the underlying Task<TResult> into the Faulted state and binds it to a specified exception.

SetException(IEnumerable<Exception>)

내부 Task<TResult>Faulted 상태로 전환하고 예외 개체 컬렉션을 바인딩합니다.Transitions the underlying Task<TResult> into the Faulted state and binds a collection of exception objects to it.

SetResult(TResult)

내부 Task<TResult>RanToCompletion 상태로 전환합니다.Transitions the underlying Task<TResult> into the RanToCompletion state.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.Returns a string that represents the current object.

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

내부 Task<TResult>Canceled 상태로 전환하려고 시도합니다.Attempts to transition the underlying Task<TResult> into the Canceled state.

TrySetCanceled(CancellationToken)

내부 Task<TResult>Canceled 상태로 전환하려고 시도하고 취소 토큰을 취소된 작업에 저장할 수 있도록 합니다.Attempts to transition the underlying Task<TResult> into the Canceled state and enables a cancellation token to be stored in the canceled task.

TrySetException(Exception)

내부 Task<TResult>Faulted 상태로 전환하고 지정된 예외에 바인딩하려고 합니다.Attempts to transition the underlying Task<TResult> into the Faulted state and binds it to a specified exception.

TrySetException(IEnumerable<Exception>)

내부 Task<TResult>Faulted 상태로 전환하고 예외 개체 컬렉션을 바인딩하려고 합니다.Attempts to transition the underlying Task<TResult> into the Faulted state and binds a collection of exception objects to it.

TrySetResult(TResult)

내부 Task<TResult>RanToCompletion 상태로 전환하려고 시도합니다.Attempts to transition the underlying Task<TResult> into the RanToCompletion state.

적용 대상

스레드 보안

모든 멤버 TaskCompletionSource<TResult> 는 스레드로부터 안전 하 고 여러 스레드에서 동시에 사용할 수 있습니다.All members of TaskCompletionSource<TResult> are thread-safe and may be used from multiple threads concurrently.

추가 정보