Task/ValueTask and the async state machine (concepts)
Understand Task results and the async state machine idea. Write tiny async methods, compose awaits, and see a manual TaskCompletionSource.
Mental model
Aim: Build intuition for async.
- Task represents ongoing work and a future result
- await pauses and later resumes
- Compiler creates a state machine
- ValueTask: newer optimization (concept only here)
Async method basics
An async method returns Task<T> immediately; later it completes with the value when awaited work finishes.
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
// Tiny async method: returns Task<int>
static async Task<int> GetAnswerAsync()
{
// Offload simple work to a thread-pool task (demo only)
int value = await Task.Run(() =>
{
Thread.Sleep(200); // simulate work
return 42;
});
return value; // completes Task<int>
}
public static void Main(string[] args)
{
// In C# 6, Main cannot be async; block just for demo (console apps are safe here)
int result = GetAnswerAsync().Result;
Console.WriteLine("Answer = " + result);
}
}
All lessons in this course
- Task/ValueTask and the async state machine (concepts)
- Async pitfalls: sync-over-async and deadlocks
- ConfigureAwait, exception flow