AsyncStateMachineAttribute Klasa

Definicja

Wskazuje, czy metoda jest oznaczona za pomocą modyfikatora asynchronicznego lub asynchronicznego .

public ref class AsyncStateMachineAttribute sealed : System::Runtime::CompilerServices::StateMachineAttribute
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false, Inherited=false)]
public sealed class AsyncStateMachineAttribute : System.Runtime.CompilerServices.StateMachineAttribute
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false, Inherited=false)]
[System.Serializable]
public sealed class AsyncStateMachineAttribute : System.Runtime.CompilerServices.StateMachineAttribute
[<System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false, Inherited=false)>]
type AsyncStateMachineAttribute = class
    inherit StateMachineAttribute
[<System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false, Inherited=false)>]
[<System.Serializable>]
type AsyncStateMachineAttribute = class
    inherit StateMachineAttribute
Public NotInheritable Class AsyncStateMachineAttribute
Inherits StateMachineAttribute
Dziedziczenie
AsyncStateMachineAttribute
Atrybuty

Przykłady

Jak pokazano w poniższym przykładzie, można określić, czy metoda jest oznaczona za pomocą modyfikatora asynchronicznego , czy asynchronicznego . W tym przykładzie IsAsyncMethod wykonasz następujące kroki:

  • MethodInfo Uzyskuje obiekt dla nazwy metody przy użyciu metody Type.GetMethod.

  • Uzyskuje Type obiekt dla atrybutu za pomocą operatora GetType lub typeof.

  • Uzyskuje obiekt atrybutu dla metody i typu atrybutu przy użyciu polecenia MethodInfo.GetCustomAttribute. Jeśli GetCustomAttribute metoda zwraca Nothing wartość (Visual Basic) lub null (C#), metoda nie zawiera atrybutu.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;

namespace ConsoleApplication1
{

    // This class is used by the code below to discover method attributes.
    public class TheClass
    {
        public async Task<int> AsyncMethod()
        {
            await Task.Delay(5);
            return 1;
        }

        public int RegularMethod()
        {
            return 0;
        }
    }

    class Program
    {
        private static bool IsAsyncMethod(Type classType, string methodName)
        {
            // Obtain the method with the specified name.
            MethodInfo method = classType.GetMethod(methodName);

            Type attType = typeof(AsyncStateMachineAttribute);

            // Obtain the custom attribute for the method.
            // The value returned contains the StateMachineType property.
            // Null is returned if the attribute isn't present for the method.
            var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType);

            return (attrib != null);
        }

        private static void ShowResult(Type classType, string methodName)
        {
            Console.Write((methodName + ": ").PadRight(16));

            if (IsAsyncMethod(classType, methodName))
                Console.WriteLine("Async method");
            else
                Console.WriteLine("Regular method");
        }

        static void Main(string[] args)
        {
            ShowResult(classType: typeof(TheClass), methodName: "AsyncMethod");
            ShowResult(classType: typeof(TheClass), methodName: "RegularMethod");

            // Note: The IteratorStateMachineAttribute applies to Visual Basic methods
            // but not C# methods.

            Console.ReadKey();
        }

        // Output:
        //   AsyncMethod:    Async method
        //   RegularMethod:  Regular method
    }
}
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices


Module Module1

    ' This class is used by the code below to discover method attributes.
    Public Class TheClass
        Public Async Function AsyncMethod() As Task(Of Integer)
            Await Task.Delay(5)
            Return 1
        End Function

        Public Iterator Function IteratorMethod() As IEnumerable(Of Integer)
            Yield 1
            Yield 2
        End Function

        Public Function RegularMethod() As Integer
            Return 0
        End Function
    End Class


    Private Function IsAsyncMethod(classType As Type, methodName As String)
        ' Obtain the method with the specified name.
        Dim method As MethodInfo = classType.GetMethod(methodName)

        Dim attType As Type = GetType(AsyncStateMachineAttribute)

        Dim attrib = CType(method.GetCustomAttribute(attType), AsyncStateMachineAttribute)
        ' The above variable contains the StateMachineType property.

        Return (attrib IsNot Nothing)
    End Function

    Private Function IsIteratorMethod(classType As Type, methodName As String)
        ' Obtain the method with the specified name.
        Dim method As MethodInfo = classType.GetMethod(methodName)

        Dim attType As Type = GetType(IteratorStateMachineAttribute)

        ' Obtain the custom attribute for the method.
        ' The value returned contains the StateMachineType property.
        ' Nothing is returned if the attribute isn't present for the method.
        Dim attrib = CType(method.GetCustomAttribute(attType), IteratorStateMachineAttribute)

        Return (attrib IsNot Nothing)
    End Function

    Private Sub ShowResult(classType As Type, methodName As String)
        Console.Write((methodName & ": ").PadRight(16))

        If IsAsyncMethod(classType, methodName) Then
            Console.WriteLine("Async method")
        ElseIf IsIteratorMethod(classType, methodName) Then
            Console.WriteLine("Iterator method")
        Else
            Console.WriteLine("Regular method")
        End If

        ' Note: The IteratorStateMachineAttribute applies to Visual Basic methods
        ' but not C# methods.
    End Sub

    Sub Main()
        ShowResult(GetType(TheClass), "AsyncMethod")
        ShowResult(GetType(TheClass), "IteratorMethod")
        ShowResult(GetType(TheClass), "RegularMethod")

        Console.ReadKey()
    End Sub

    '   AsyncMethod:    Async method
    '   IteratorMethod: Iterator method
    '   RegularMethod:  Regular method

End Module

Uwagi

Nie należy stosować atrybutu AsyncStateMachine do metod w kodzie. W przypadku metod, które mają modyfikator asynchroniczny, kompilator zastosuje AsyncStateMachine atrybut w il emitowany przez kompilator.

Gdy metoda (MethodName) ma modyfikator asynchroniczny lub asynchroniczny, kompilator emituje il, który zawiera strukturę maszyny stanu. Ta struktura zawiera kod w metodzie . Ten il zawiera również metodę wycinkową (MethodName), która wywołuje metodę do maszyny stanu. Kompilator dodaje AsyncStateMachine atrybut do metody wycinka, aby narzędzia mogły zidentyfikować odpowiednią maszynę stanu. Szczegóły emitowanego il mogą ulec zmianie w przyszłych wersjach kompilatorów.

Aby uzyskać informacje na temat funkcji asynchronicznej, zobacz Programowanie asynchroniczne (C#) lub Programowanie asynchroniczne przy użyciu Async i Await (Visual Basic).

Konstruktory

AsyncStateMachineAttribute(Type)

Inicjuje nowe wystąpienie klasy AsyncStateMachineAttribute.

Właściwości

StateMachineType

Zwraca obiekt typu dla bazowego typu maszyny stanu, który został wygenerowany przez kompilator w celu zaimplementowania metody maszyny stanu.

(Odziedziczone po StateMachineAttribute)
TypeId

Po zaimplementowaniu w klasie pochodnej pobiera unikatowy identyfikator dla tego Attributeelementu .

(Odziedziczone po Attribute)

Metody

Equals(Object)

Zwraca wartość wskazującą, czy to wystąpienie jest równe podanemu obiektowi.

(Odziedziczone po Attribute)
GetHashCode()

Zwraca wartość skrótu dla tego wystąpienia.

(Odziedziczone po Attribute)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
IsDefaultAttribute()

Podczas zastępowania w klasie pochodnej wskazuje, czy wartość tego wystąpienia jest wartością domyślną dla klasy pochodnej.

(Odziedziczone po Attribute)
Match(Object)

Po przesłonięciu w klasie pochodnej zwraca wartość wskazującą, czy to wystąpienie jest równe określonemu obiektowi.

(Odziedziczone po Attribute)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Jawne implementacje interfejsu

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Zestaw nazw jest mapowany na odpowiedni zestaw identyfikatorów wysyłania.

(Odziedziczone po Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Pobiera informacje o typie dla obiektu, który może służyć do pobierania informacji o typie dla interfejsu.

(Odziedziczone po Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Pobiera informację o liczbie typów interfejsów, jakie zawiera obiekt (0 lub 1).

(Odziedziczone po Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Umożliwia dostęp do właściwości i metod udostępnianych przez obiekt.

(Odziedziczone po Attribute)

Dotyczy

Zobacz też