首页 > 解决方案 > StateMachineAttribute 在 .NET 中的用途是什么?

问题描述

我遇到StateMachineAttribute文档中调用的一个类。StateMachine.NET中的用途是什么?用途是什么StateMachineAttribute

标签: .netstate-machine

解决方案


当您实现异步方法时,C# 编译器使用从 StateMachineAttribute 派生的 AsyncStateMachineAttribute 生成方法

C# 代码

...
public async Task HelloWorldAsync()
{
        await Console.Out.WriteLineAsync("Hello World!");
}
...

“真实”方法(由编译器生成)

[AsyncStateMachine(typeof(<HelloWorldAsync>d__4))]
[DebuggerStepThrough]
public Task HelloWorldAsync()
{
    <HelloWorldAsync>d__4 stateMachine = new <HelloWorldAsync>d__4();
    stateMachine.<>4__this = this;
    stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
    stateMachine.<>1__state = -1;
    AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
    <>t__builder.Start(ref stateMachine);
    return stateMachine.<>t__builder.Task;
}

编译器确实不使用 StateMachineAttribute。对于状态机方法,编译器将应用 AsyncStateMachineAttribute 或 IteratorStateMachineAttribute


推荐阅读