AsyncStateMachineAttribute Classe

Definição

Indica se um método é marcado com o modificador Async ou 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
Herança
AsyncStateMachineAttribute
Atributos

Exemplos

Como mostra o exemplo a seguir, você pode determinar se um método é marcado com modificador assíncrono ou assíncrono . No exemplo, IsAsyncMethod executa as seguintes etapas:

  • Obtém um MethodInfo objeto para o nome do método usando Type.GetMethod.

  • Obtém um Type objeto para o atributo usando o Operador GetType ou o tipo.

  • Obtém um objeto de atributo para o método e o tipo de atributo usando MethodInfo.GetCustomAttribute. Se GetCustomAttribute retornar Nothing (Visual Basic) ou null (C#), o método não conterá o 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

Comentários

Você não deve aplicar o AsyncStateMachine atributo aos métodos em seu código. Para métodos que têm o modificador assíncrono, o compilador aplicará o AsyncStateMachine atributo na IL que o compilador emite.

Quando um método (MethodName) tem o modificador Assíncrono ou assíncrono, o compilador emite IL que inclui uma estrutura de computador de estado. Essa estrutura contém o código no método. Essa IL também contém um método stub (MethodName) que chama o computador de estado. O compilador adiciona o AsyncStateMachine atributo ao método stub para que as ferramentas possam identificar o computador de estado correspondente. Os detalhes da IL emitida podem ser alterados em versões futuras dos compiladores.

Para obter informações sobre o recurso Assíncrono, consulte programação assíncrona (C#) ou programação assíncrona com Async e Await (Visual Basic).

Construtores

AsyncStateMachineAttribute(Type)

Inicializa uma nova instância da classe AsyncStateMachineAttribute.

Propriedades

StateMachineType

Retorna o objeto de tipo para o tipo de computador de estado subjacente gerado pelo compilador para implementar o método de computador de estado.

(Herdado de StateMachineAttribute)
TypeId

Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.

(Herdado de Attribute)

Métodos

Equals(Object)

Retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
GetHashCode()

Retorna o código hash para a instância.

(Herdado de Attribute)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()

Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.

(Herdado de Attribute)
Match(Object)

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

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

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

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

Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).

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

Fornece acesso a propriedades e métodos expostos por um objeto.

(Herdado de Attribute)

Aplica-se a

Confira também