本文整理汇总了C#中System.Runtime.CompilerServices.AsyncStateMachineAttribute类的典型用法代码示例。如果您正苦于以下问题:C# AsyncStateMachineAttribute类的具体用法?C# AsyncStateMachineAttribute怎么用?C# AsyncStateMachineAttribute使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
AsyncStateMachineAttribute类属于System.Runtime.CompilerServices命名空间,在下文中一共展示了AsyncStateMachineAttribute类的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AsyncMethod
//引入命名空间
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
}
}