Async/Await Keywords
async: Marks a method as asynchronous.
await: Pauses the execution of the method until the awaited task completes, freeing up the thread to handle other work.
Tasks (Task and Task<T>):
Task: Represents an asynchronous operation that does not return a value.
Task<T>: Represents an asynchronous operation that returns a value of type T.
Threading in Async:
Asynchronous APIs do not create new threads; they use the existing thread pool efficiently.
For I/O-bound operations, the thread is freed while waiting for the I/O to complete.
Scenarios for Async APIs:
I/O-Bound Work: APIs like HttpClient.GetAsync, DbContext.ToListAsync.
CPU-Bound Work: Parallel processing using Task.Run
Why Use Async APIs?
Better Scalability:
- Async APIs allow servers to handle more requests by freeing up threads when waiting for I/O-bound operations.
Improved Responsiveness:
- For UI applications, async prevents the UI from freezing during long operations.
Efficient Resource Usage:
- Threads are used efficiently, minimizing CPU time and context switching.
Best Practices
- Always use
async/await
for I/O-bound operations like database calls or HTTP requests. - Propagate
Task
rather than blocking calls. - Ensure proper exception handling with
try-catch
. - Avoid unnecessary use of
Task.Run
for operations that are already asynchronous.
No comments:
Post a Comment