{{theTime}}

Search This Blog

Total Pageviews

.Net Async APIs

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?

  1. Better Scalability:

    • Async APIs allow servers to handle more requests by freeing up threads when waiting for I/O-bound operations.
  2. Improved Responsiveness:

    • For UI applications, async prevents the UI from freezing during long operations.
  3. Efficient Resource Usage:

    • Threads are used efficiently, minimizing CPU time and context switching.

Best Practices

  1. Always use async/await for I/O-bound operations like database calls or HTTP requests.
  2. Propagate Task rather than blocking calls.
  3. Ensure proper exception handling with try-catch.
  4. Avoid unnecessary use of Task.Run for operations that are already asynchronous.

No comments:

Generate Insert Sql from Select Statement

SELECT 'INSERT INTO ReferenceTable (ID, Name) VALUES (' +        CAST(ID AS NVARCHAR) + ', ''' + Name + ''...