Skip to content

async and await

Question

Describe the mechanism of async and await.

Short interview answer

async enables await in a method. Awaiting an incomplete task suspends the method and returns control to its caller; the compiler-generated state machine resumes it when the task completes.

Detailed answer

For I/O, await the asynchronous API directly so the calling thread is not blocked. For CPU-bound work that should not occupy a UI thread, use an appropriate background-work strategy such as Task.Run. async does not automatically create a thread; it expresses asynchronous composition around Task or other awaitable operations.

For example, var invoice = await client.GetFromJsonAsync<Invoice>(url, cancellationToken); returns control while the HTTP request is pending; the next line runs only after it produces an invoice, throws, or observes cancellation.

Sources