Task and async/await
Task and async/await
A Task represents an operation that can finish successfully, fail or be canceled. Task<T> additionally carries a result of type T. An async method can await unfinished work without holding its caller in a synchronous wait. Async is not a promise of a new thread or faster computation.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. File examples require an authorized disposable environment with a writable temporary directory and no concurrent writers.
Await a result
An already completed task provides its result immediately when awaited. A method marked async runs synchronously up to its first incomplete await, unless it returns or throws earlier.
using System;using System.Threading.Tasks;int total = await QuoteAsync();Console.WriteLine(total);static async Task<int> QuoteAsync(){ int units = await Task.FromResult(3); return units * 4;}Task.FromResult provides an already completed task; no suspension or extra thread is needed.
Expected output (reasoned, not executed):
12Observe suspension without sleeping
TaskCompletionSource<T> lets a test or adapter control the completion of a task. This fixture completes a single gate explicitly. Statements before an incomplete await run before control returns to the caller.
using System;using System.Threading.Tasks;var gate = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);Task<int> work = DoubleAsync(gate.Task);Console.WriteLine(work.IsCompleted);gate.SetResult(5);Console.WriteLine(await work);static async Task<int> DoubleAsync(Task<int> input){ Console.WriteLine("Started"); int value = await input; return value * 2;}The task cannot complete until the gate supplies its value. Awaiting work observes the result after completion, independent of scheduler timing.
Expected output (reasoned, not executed):
StartedFalse10Await asynchronous file I/O
File.WriteAllTextAsync and File.ReadAllTextAsync return tasks. Await each operation before using its output or deleting its resources. The platform may complete the task immediately or asynchronously; the example does not assume a particular scheduling mechanism.
using System;using System.IO;var folder = Directory.CreateTempSubdirectory("bytemind-");string path = Path.Combine(folder.FullName, "note.txt");try{ await File.WriteAllTextAsync(path, "Ready"); string text = await File.ReadAllTextAsync(path); Console.WriteLine(text);}finally { File.Delete(path); folder.Delete(); }The read starts only after the write has completed, and cleanup happens after both operations finish or a failure propagates.
Expected output (reasoned, not executed):
ReadyCommon mistakes and edge cases
Use Task or Task<T> for ordinary asynchronous methods so callers can observe completion and failure. Reserve async void for event handlers where a void signature is required, and handle errors there. Do not substitute .Result or .Wait() for await as a default; blocking can waste threads and cause deadlocks in some contexts. CPU-bound parallel work is a separate design choice; an async keyword alone does not offload CPU work.
Practice and recap
Change the gate example to triple the input and complete it with 7. Predict all lines and explain why no fixed sleep is needed.
Hint: The gate is incomplete before SetResult, then supplies a known value.
Learning objective: Explain completion, suspension and result propagation. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Task and async/await — knowledge check
Apply the lesson concepts to the following scenarios.
What does Task<int> represent?
What happens when awaiting a completed task?
When does DoubleAsync print Started?
Why await WriteAllTextAsync before reading the file?
Which return type is preferred for normal async methods with no value?