COMPUTER ENGINEER

Jump to examples
Blog
Next.js / ASP.NET Core / SQL6 min study
33/ 41

Performance and caching

async/await, the thread pool and scaling

Async does not make code faster; it frees the thread while waiting so more requests can be served.

UnderstandStudy an examplePractise

Understand the concept

ASP.NET Core handles requests on thread pool threads. While a request waits for the database or another service, synchronous code keeps the thread pointlessly busy. await returns the thread to the pool while waiting; when the operation completes, execution may continue on another thread. The same number of threads therefore serves many more concurrent requests.

That is why every I/O call should be async: ToListAsync, SaveChangesAsync, HttpClient.GetAsync, ReadAsync. Async methods should stay async all the way up the chain. Blocking on an async method with .Result or .Wait() (sync-over-async) locks the thread; under load the thread pool starves and the app stops responding even though the CPU is idle.

A CancellationToken stops work when the client disconnects or a timeout occurs. ASP.NET Core provides one per request (HttpContext.RequestAborted or an action parameter). Passing it to EF Core and HttpClient calls prevents queries nobody is waiting for from running in vain.

WHEN TO USE IT

Thread pool starvation is one of the most common reasons an app suddenly freezes under load.

COMMON PITFALL

Blocking on an async call with .Result or using async void.

01 / PRACTICE

One topic. Three levels of depth.

Illustrative example
// ✗ Senkron: bekleme süresince iş parçacığı meşgul
var posts = db.Posts.ToList();

// ✓ Async: bekleme süresince iş parçacığı serbest
var posts = await db.Posts.ToListAsync(ct);

The result is the same; the difference is what the thread does while waiting.

This page connects to no real server or database. Code samples are illustrative for .NET 8, Next.js and SQL Server; timings are example values in the simulation, not measurements. Try samples only in your own development environment; never share real connection strings, tokens or passwords.

02 / YOUR TURN

Try it yourself first.

In a load test with 200 concurrent users response times hit 30 seconds, CPU is 15%, the database is relaxed. What do you look for in the code?

Show the solution and explanation
Worked solution
.Result / .Wait() / GetAwaiter().GetResult() kullanımları,
senkron G/Ç (File.ReadAllText, ToList, SaveChanges),
Thread.Sleep. Hepsi iş parçacığını kilitler → thread pool açlığı.

A system waiting while resources are idle points to blocked threads.