Reputation: 11599
I came across a class called StateMachineAttribute
in the documentation. What is the purpose of StateMachine
in .NET and what StateMachineAttribute
is used for?
Upvotes: 0
Views: 858
Reputation: 2216
When you implement async method, C# compiler generate method with AsyncStateMachineAttribute that is derived from StateMachineAttribute
C# code
...
public async Task HelloWorldAsync()
{
await Console.Out.WriteLineAsync("Hello World!");
}
...
"Real" method (generated by compiler)
[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;
}
Really StateMachineAttribute isn't used by compiler. For methods that are state machine methods, the compiler will apply the AsyncStateMachineAttribute or IteratorStateMachineAttribute
Upvotes: 1