AsyncStateMachineAttribute Clase

Definición

Indica si un método está marcado con el modificador Async o el modificador async.

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
Herencia
AsyncStateMachineAttribute
Atributos

Ejemplos

Como se muestra en el ejemplo siguiente, puede determinar si un método está marcado con un modificador asincrónico o asincrónico . En el ejemplo, IsAsyncMethod realiza los pasos siguientes:

  • Obtiene un MethodInfo objeto para el nombre del método mediante Type.GetMethod.

  • Obtiene un Type objeto para el atributo mediante GetType Operator o typeof.

  • Obtiene un objeto de atributo para el método y el tipo de atributo mediante MethodInfo.GetCustomAttribute. Si GetCustomAttribute devuelve Nothing (Visual Basic) o null (C#), el método no contiene el atributo .

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

Comentarios

No debe aplicar el AsyncStateMachine atributo a los métodos del código. En el caso de los métodos que tienen el modificador asincrónico, el compilador aplicará el AsyncStateMachine atributo en el IL que emite el compilador.

Cuando un método (MethodName) tiene el modificador asincrónico o asincrónico, el compilador emite IL que incluye una estructura de máquina de estado. Esta estructura contiene el código del método . Ese IL también contiene un método de código auxiliar (MethodName) que llama a en la máquina de estado. El compilador agrega el AsyncStateMachine atributo al método de código auxiliar para que las herramientas puedan identificar la máquina de estado correspondiente. Los detalles del IL emitido pueden cambiar en futuras versiones de los compiladores.

Para obtener información sobre la característica asincrónica, vea Programación asincrónica (C#) o Programación asincrónica con Async y Await (Visual Basic).

Constructores

AsyncStateMachineAttribute(Type)

Inicializa una nueva instancia de la clase AsyncStateMachineAttribute.

Propiedades

StateMachineType

Devuelve el objeto de tipo para el tipo de equipo de estado subyacente generado por el compilador para implementar el método de equipo de estado.

(Heredado de StateMachineAttribute)
TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.

(Heredado de Attribute)

Métodos

Equals(Object)

Devuelve un valor que indica si esta instancia es igual que un objeto especificado.

(Heredado de Attribute)
GetHashCode()

Devuelve el código hash de esta instancia.

(Heredado de Attribute)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
IsDefaultAttribute()

Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.

(Heredado de Attribute)
Match(Object)

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.

(Heredado de Attribute)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

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

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.

(Heredado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Obtiene la información de tipos de un objeto, que puede utilizarse para obtener la información de tipos de una interfaz.

(Heredado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).

(Heredado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.

(Heredado de Attribute)

Se aplica a

Consulte también