AsyncStateMachineAttribute Класс
В этой статье
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
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
- Наследование
- Атрибуты
Примеры
Как показано в следующем примере, можно определить, помечен ли метод модификатором Async или async . В этом примере выполняется следующее IsAsyncMethod
:
Получает MethodInfo объект для имени метода с помощью Type.GetMethod.
Получает Type объект для атрибута с помощью оператора GetType или typeof.
Получает объект атрибута для метода и типа атрибута с помощью
MethodInfo.GetCustomAttribute
. ЕслиGetCustomAttribute
возвращает значениеNothing
(Visual Basic) илиnull
(C#), метод не содержит атрибут .
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
Комментарии
Атрибут не следует применять AsyncStateMachine
к методам в коде. Для методов с асинхронным модификатором компилятор применит AsyncStateMachine
атрибут в il, который выдает компилятор.
Если метод (Имя_метода) имеет модификатор Async или async, компилятор выдает il, включающий структуру конечного автомата. Эта структура содержит код в методе . Этот IL также содержит метод заглушки (Имя_метода), который вызывает конечный автомат. Компилятор добавляет атрибут в AsyncStateMachine
метод заглушки, чтобы средства могли идентифицировать соответствующий конечный автомат. Сведения о выдаваемом IL могут измениться в будущих выпусках компиляторов.
Сведения о функции асинхронного программирования см. в разделах Асинхронное программирование (C#) или Асинхронное программирование с помощью Async и Await (Visual Basic).
Конструкторы
Async |
Инициализирует новый экземпляр класса AsyncStateMachineAttribute. |
Свойства
State |
Возвращает объект типа для типа базового конечного автомата, который был создан компилятором для реализации метода конечного автомата. (Унаследовано от StateMachineAttribute) |
Type |
В случае реализации в производном классе возвращает уникальный идентификатор для этого атрибута Attribute. (Унаследовано от Attribute) |
Методы
Equals(Object) |
Возвращает значение, показывающее, равен ли экземпляр указанному объекту. (Унаследовано от Attribute) |
Get |
Возвращает хэш-код данного экземпляра. (Унаследовано от Attribute) |
Get |
Возвращает объект Type для текущего экземпляра. (Унаследовано от Object) |
Is |
При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса. (Унаследовано от Attribute) |
Match(Object) |
При переопределении в производном классе возвращает значение, указывающее, является ли этот экземпляр равным заданному объекту. (Унаследовано от Attribute) |
Memberwise |
Создает неполную копию текущего объекта Object. (Унаследовано от Object) |
To |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
Явные реализации интерфейса
_Attribute. |
Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации. (Унаследовано от Attribute) |
_Attribute. |
Возвращает сведения о типе объекта, которые можно использовать для получения сведений о типе интерфейса. (Унаследовано от Attribute) |
_Attribute. |
Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1). (Унаследовано от Attribute) |
_Attribute. |
Предоставляет доступ к открытым свойствам и методам объекта. (Унаследовано от Attribute) |
Применяется к
Продукт | Версии |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10 |
.NET Framework | 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1 |
UWP | 10.0 |