AsyncLocal<T> 클래스

정의

비동기 메서드와 같은 지정된 비동기 제어 흐름에 로컬인 앰비언트 데이터를 나타냅니다.Represents ambient data that is local to a given asynchronous control flow, such as an asynchronous method.

generic <typename T>
public ref class AsyncLocal sealed
public sealed class AsyncLocal<T>
type AsyncLocal<'T> = class
Public NotInheritable Class AsyncLocal(Of T)

형식 매개 변수

T

앰비언트 데이터의 형식입니다.The type of the ambient data.

상속
AsyncLocal<T>

예제

다음 예제에서는 클래스를 사용 AsyncLocal<T> 하 여 비동기 흐름에서 문자열 값을 유지 합니다.The following example uses the AsyncLocal<T> class to persist a string value across an asynchronous flow. 또한의 사용과를 대조 AsyncLocal<T> ThreadLocal<T> 합니다.It also contrasts the use of AsyncLocal<T> with ThreadLocal<T>.

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

class Example
{
    static AsyncLocal<string> _asyncLocalString = new AsyncLocal<string>();

    static ThreadLocal<string> _threadLocalString = new ThreadLocal<string>();

    static async Task AsyncMethodA()
    {
        // Start multiple async method calls, with different AsyncLocal values.
        // We also set ThreadLocal values, to demonstrate how the two mechanisms differ.
        _asyncLocalString.Value = "Value 1";
        _threadLocalString.Value = "Value 1";
        var t1 = AsyncMethodB("Value 1");

        _asyncLocalString.Value = "Value 2";
        _threadLocalString.Value = "Value 2";
        var t2 = AsyncMethodB("Value 2");

        // Await both calls
        await t1;
        await t2;
     }

    static async Task AsyncMethodB(string expectedValue)
    {
        Console.WriteLine("Entering AsyncMethodB.");
        Console.WriteLine("   Expected '{0}', AsyncLocal value is '{1}', ThreadLocal value is '{2}'", 
                          expectedValue, _asyncLocalString.Value, _threadLocalString.Value);
        await Task.Delay(100);
        Console.WriteLine("Exiting AsyncMethodB.");
        Console.WriteLine("   Expected '{0}', got '{1}', ThreadLocal value is '{2}'", 
                          expectedValue, _asyncLocalString.Value, _threadLocalString.Value);
    }

    static async Task Main(string[] args)
    {
        await AsyncMethodA();
    }
}
// The example displays the following output:
//   Entering AsyncMethodB.
//      Expected 'Value 1', AsyncLocal value is 'Value 1', ThreadLocal value is 'Value 1'
//   Entering AsyncMethodB.
//      Expected 'Value 2', AsyncLocal value is 'Value 2', ThreadLocal value is 'Value 2'
//   Exiting AsyncMethodB.
//      Expected 'Value 2', got 'Value 2', ThreadLocal value is ''
//   Exiting AsyncMethodB.
//      Expected 'Value 1', got 'Value 1', ThreadLocal value is ''
Imports System.Threading
Imports System.Threading.Tasks

Module Example
    Dim _asyncLocalString As New AsyncLocal(Of String)()

    Dim _threadLocalString As New ThreadLocal(Of String)()

    Async Function AsyncMethodA() As Task
        ' Start multiple async method calls, with different AsyncLocal values.
        ' We also set ThreadLocal values, to demonstrate how the two mechanisms differ.
        _asyncLocalString.Value = "Value 1"
        _threadLocalString.Value = "Value 1"
        Dim t1 = AsyncMethodB("Value 1")

        _asyncLocalString.Value = "Value 2"
        _threadLocalString.Value = "Value 2"
        Dim t2 = AsyncMethodB("Value 2")

        ' Await both calls
        await t1
        await t2
     End Function

    Async Function AsyncMethodB(expectedValue As String) As Task
        Console.WriteLine("Entering AsyncMethodB.")
        Console.WriteLine("   Expected '{0}', AsyncLocal value is '{1}', ThreadLocal value is '{2}'", 
                          expectedValue, _asyncLocalString.Value, _threadLocalString.Value)
        await Task.Delay(100)
        Console.WriteLine("Exiting AsyncMethodB.")
        Console.WriteLine("   Expected '{0}', got '{1}', ThreadLocal value is '{2}'", 
                          expectedValue, _asyncLocalString.Value, _threadLocalString.Value)
    End Function

   Public Sub Main()
       AsyncMethodA.Wait()
   End Sub
End Module
' The example displays the following output:
'   Entering AsyncMethodB.
'      Expected 'Value 1', AsyncLocal value is 'Value 1', ThreadLocal value is 'Value 1'
'   Entering AsyncMethodB.
'      Expected 'Value 2', AsyncLocal value is 'Value 2', ThreadLocal value is 'Value 2'
'   Exiting AsyncMethodB.
'      Expected 'Value 2', got 'Value 2', ThreadLocal value is ''
'   Exiting AsyncMethodB.
'      Expected 'Value 1', got 'Value 1', ThreadLocal value is ''

설명

작업 기반 비동기 프로그래밍 모델은 스레드 사용을 추상화 하는 경향이 있기 때문에 AsyncLocal<T> 인스턴스를 사용 하 여 스레드 간에 데이터를 유지할 수 있습니다.Because the task-based asynchronous programming model tends to abstract the use of threads, AsyncLocal<T> instances can be used to persist data across threads.

AsyncLocal<T>또한 클래스는 현재 스레드와 연결 된 값이 변경 될 때 (속성을 설정 하 여 명시적으로 변경 되었거나 Value 스레드에서 await 또는 다른 컨텍스트 전환이 발생 했을 때 암시적으로 변경 되었기 때문에) 선택적 알림을 제공 합니다.The AsyncLocal<T> class also provides optional notifications when the value associated with the current thread changes, either because it was explicitly changed by setting the Value property, or implicitly changed when the thread encountered an await or other context transition.

생성자

AsyncLocal<T>()

변경 알림을 받지 않는 AsyncLocal<T> 인스턴스를 인스턴스화합니다.Instantiates an AsyncLocal<T> instance that does not receive change notifications.

AsyncLocal<T>(Action<AsyncLocalValueChangedArgs<T>>)

변경 알림을 받는 AsyncLocal<T> 로컬 인스턴스를 인스턴스화합니다.Instantiates an AsyncLocal<T> local instance that receives change notifications.

속성

Value

앰비언트 데이터의 값을 가져오거나 설정합니다.Gets or sets the value of the ambient data.

메서드

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)
ToString()

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

(다음에서 상속됨 Object)

적용 대상