A lot of us have been using async-await and Task when writing C#. For me, it is very important to understand what is happening under the hood when writing asynchronous code so in this post, let’s explore state machines.

What Is a State Machine?

A state machine, or finite state machine (FSM), is a computational model used to design algorithms. It consists of a finite number of states, transitions between those states, and actions that occur as a result of those transitions. State machines are highly effective for modeling behavior in systems where an entity can be in one of several distinct states, each with specific rules for transitioning to other states.

Let’s make it simpler. Imagine a traffic light can be thought of as a state machine. How?

The traffic light can be in one of the following states:

  1. Green Light
  2. Yellow Light
  3. Red Light

The transitions between these states occur in a specific sequence, often based on timing or sensor inputs:

  • Green to Yellow: After the green light has been on for a certain period, the system transitions to yellow.
  • Yellow to Red: After the yellow light has been on briefly, it transitions to red.
  • Red to Green: After the red light has been on for a set duration, it transitions back to green.

Events/Inputs

While a basic traffic light operates on a timed sequence, more advanced systems might consider additional inputs:

  • Pedestrian Button Pressed: Triggers a transition to red to allow pedestrians to cross.
  • Traffic Sensors: Adjusts the timing based on the presence or absence of vehicles.

The traffic light example demonstrates how a state machine operates with defined states and transitions. When writing asynchronous code in .NET, the compiler-generated state machines work similarly:

  • States: Correspond to different points in the asynchronous method where execution can pause and resume.
  • Transitions: Managed by the compiler to resume execution after await operations complete.
  • Events/Inputs: The completion of tasks or external events that trigger the continuation of the method.

Asynchronous Programming in .NET

In .NET, asynchronous programming is primarily handled using the async and await keywords. These keywords allow developers to write code that performs non-blocking operations without the complexity traditionally associated with asynchronous code.

public async Task<Data> GetDataAsync()
{
    var data = await FetchDataFromDatabaseAsync();
    return data;
}

When you use await, the method doesn’t block; instead, it yields control back to the calling method, allowing other operations to run!!!

How the Compiler Generates State Machines

While async and await make asynchronous programming straightforward, they hide the complexity involved in managing asynchronous operations. The C# compiler transforms your asynchronous methods into state machines to handle the control flow.

What Happens Under the Hood:

  1. Method Transformation: The asynchronous method is converted into a state machine structure, usually a generated class implementing IAsyncStateMachine.
  2. State Management: The compiler introduces a state variable to keep track of where the method should resume after an await.
  3. Continuation Logic: The method’s logic is split into different states, and transitions are handled based on the completion of awaited tasks.

    If you want to see how an asynchronous method is being transformed, you can check it out at sharplab.io

    I didn’t paste any code here because it would have been TOO much but let’s just say we ‘re lucky that using Tasks with async and await are syntactic sugar for this.

Conclusion

Understanding that your asynchronous methods are transformed into state machines by the compiler can deepen your insight into how asynchronous programming works in .NET. While the async and await keywords simplify the syntax, appreciating the underlying mechanics can help you write more efficient and effective asynchronous code.

Affiliate promo

If you love learning new stuff and want to support me, consider buying a course from Dometrain using this link: Browse courses – Dometrain. Thank you!

Leave a comment

Trending