How to Use Async Await in C#: Simple Guide
async to mark a method as asynchronous and await to pause execution until a task completes without blocking the thread. This lets your program run other work while waiting for long tasks like file reading or web requests.Syntax
The async keyword is added before the method return type to declare it as asynchronous. Inside this method, use await before a call to a method that returns a Task or Task<T>. This pauses the method until the awaited task finishes, then resumes with the result.
- async: marks the method as asynchronous
- await: waits for the task to complete without blocking
- Task: represents an ongoing operation
- Task<T>: represents an ongoing operation that returns a value
public async Task<int> GetNumberAsync() { await Task.Delay(1000); // wait 1 second asynchronously return 42; }
Example
This example shows an asynchronous method that waits 2 seconds and then returns a message. The Main method calls it with await and prints the result. The program does not freeze while waiting.
using System; using System.Threading.Tasks; class Program { static async Task Main() { string message = await GetMessageAsync(); Console.WriteLine(message); } static async Task<string> GetMessageAsync() { await Task.Delay(2000); // simulate work return "Hello after 2 seconds!"; } }
Common Pitfalls
Common mistakes include forgetting to mark a method async when using await, which causes compile errors. Another is using async void methods outside event handlers, which makes error handling difficult. Also, blocking calls like .Result or .Wait() on async tasks can cause deadlocks.
/* Wrong way: missing async keyword */ // static Task<string> GetData() // { // await Task.Delay(1000); // Error: await only valid in async method // return "data"; // } /* Right way: */ static async Task<string> GetData() { await Task.Delay(1000); return "data"; } /* Avoid async void except for event handlers */ // async void DoWork() { await Task.Delay(1000); } // Hard to catch errors /* Prefer async Task instead */ async Task DoWorkAsync() { await Task.Delay(1000); }
Quick Reference
Remember these tips when using async and await in C#:
- Mark methods with
asyncto useawaitinside. - Use
TaskorTask<T>as return types for async methods. - Use
awaitto pause without blocking the thread. - Avoid
async voidexcept for event handlers. - Do not block async calls with
.Resultor.Wait().
Key Takeaways
async to mark methods that run asynchronously.await to wait for tasks without blocking the program.Task or Task<T>, not void..Result or .Wait().