Skip to content

Instantly share code, notes, and snippets.

@admir-live
Created September 6, 2023 06:18
Show Gist options
  • Save admir-live/16b8962866031d08d9b023718bfca63a to your computer and use it in GitHub Desktop.
Save admir-live/16b8962866031d08d9b023718bfca63a to your computer and use it in GitHub Desktop.
public class StateMachineExamples
{
// Inefficient use of async
public async Task<string> InefficientMethodAsync()
{
// This method is marked as async, but it lacks any await statements.
// As a result, the compiler generates a state machine which is unnecessary.
return "Hello, World!";
}
// Efficient alternative
public Task<string> EfficientMethod()
{
// Without the async keyword, the method directly returns a completed task.
// No state machine is generated, which makes it more memory-efficient.
return Task.FromResult("Hello, World!");
}
}
// In summary:
// 1. The async keyword instructs the compiler to generate a state machine.
// 2. This state machine handles the mechanics of pausing and resuming a method's execution around await points.
// 3. If there are no await points (i.e., no asynchronous operations), the state machine is unnecessary.
// 4. In high-throughput scenarios, unnecessary state machines can contribute to memory pressure and negatively affect performance.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment