AsyncStateMachineAttribute Classe
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
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
- Ereditarietà
- Attributi
Esempio
Come illustrato nell'esempio seguente, è possibile determinare se un metodo è contrassegnato con il modificatore asincrono o asincrono. Nell'esempio viene IsAsyncMethod
eseguita la procedura seguente:
Ottiene un MethodInfo oggetto per il nome del metodo utilizzando Type.GetMethod.
Ottiene un Type oggetto per l'attributo utilizzando GetType Operator o typeof.
Ottiene un oggetto attributo per il metodo e il tipo di attributo usando
MethodInfo.GetCustomAttribute
. SeGetCustomAttribute
restituisceNothing
(Visual Basic) onull
(C#), il metodo non contiene l'attributo .
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
Commenti
Non è consigliabile applicare l'attributo AsyncStateMachine
ai metodi nel codice. Per i metodi che hanno il modificatore asincrono, il compilatore applicherà l'attributo AsyncStateMachine
nel codice IL generato dal compilatore.
Quando un metodo (MethodName) ha il modificatore asincrono o asincrono, il compilatore genera IL che include una struttura della macchina a stati. Questa struttura contiene il codice nel metodo . Tale IL contiene anche un metodo stub (MethodName) che chiama nella macchina a stati. Il compilatore aggiunge l'attributo AsyncStateMachine
al metodo stub in modo che gli strumenti possano identificare la macchina a stati corrispondente. I dettagli dell'il generato potrebbero cambiare nelle versioni future dei compilatori.
Per informazioni sulla funzionalità asincrona, vedere Programmazione asincrona (C#) o Programmazione asincrona con Async e Await (Visual Basic).
Costruttori
AsyncStateMachineAttribute(Type) |
Inizializza una nuova istanza della classe AsyncStateMachineAttribute. |
Proprietà
StateMachineType |
Restituisce l'oggetto tipo per il tipo sottostante della macchina a stati generato dal compilatore per implementare il metodo della macchina a stati. (Ereditato da StateMachineAttribute) |
TypeId |
Quando è implementata in una classe derivata, ottiene un identificatore univoco della classe Attribute. (Ereditato da Attribute) |
Metodi
Equals(Object) |
Restituisce un valore che indica se questa istanza è uguale a un oggetto specificato. (Ereditato da Attribute) |
GetHashCode() |
Restituisce il codice hash per l'istanza. (Ereditato da Attribute) |
GetType() |
Ottiene l'oggetto Type dell'istanza corrente. (Ereditato da Object) |
IsDefaultAttribute() |
In caso di override in una classe derivata, indica se il valore di questa istanza è il valore predefinito per la classe derivata. (Ereditato da Attribute) |
Match(Object) |
Quando è sottoposto a override in una classe derivata, restituisce un valore che indica se questa istanza equivale a un oggetto specificato. (Ereditato da Attribute) |
MemberwiseClone() |
Crea una copia superficiale dell'oggetto Object corrente. (Ereditato da Object) |
ToString() |
Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object) |
Implementazioni dell'interfaccia esplicita
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Esegue il mapping di un set di nomi a un set corrispondente di ID dispatch. (Ereditato da Attribute) |
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera le informazioni sul tipo relative a un oggetto, che possono essere usate per ottenere informazioni sul tipo relative a un'interfaccia. (Ereditato da Attribute) |
_Attribute.GetTypeInfoCount(UInt32) |
Recupera il numero delle interfacce di informazioni sul tipo fornite da un oggetto (0 o 1). (Ereditato da Attribute) |
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fornisce l'accesso a proprietà e metodi esposti da un oggetto. (Ereditato da Attribute) |
Si applica a
Vedi anche
Commenti e suggerimenti
https://aka.ms/ContentUserFeedback.
Presto disponibile: Nel corso del 2024 verranno gradualmente disattivati i problemi di GitHub come meccanismo di feedback per il contenuto e ciò verrà sostituito con un nuovo sistema di feedback. Per altre informazioni, vedereInvia e visualizza il feedback per