Almost every piece of concurrent code you write in .NET runs on the ThreadPool, even when you never type the word. Task.Run uses it. The continuation after an await usually runs on it. Every request that hits an ASP.NET Core app is handled on it. Understanding the ThreadPool explains why async code scales, why blocking calls hurt a web server so badly and when it actually makes sense to create a thread of your own. This article starts from what a thread costs, builds up to what the pool does about that cost and then follows the pool through Task.Run, LongRunning, async/await and ASP.NET Core. If you are not yet sure what a thread is or how it differs from a Task, start with the previous article, Threads and Tasks in .NET.

Σχεδόν κάθε κομμάτι concurrent κώδικα που γράφεις στο .NET τρέχει πάνω στο ThreadPool, ακόμα κι αν δεν γράψεις ποτέ αυτή τη λέξη. Το Task.Run το χρησιμοποιεί. Το continuation μετά από ένα await συνήθως τρέχει πάνω του. Κάθε request που φτάνει σε μια εφαρμογή ASP.NET Core εξυπηρετείται πάνω του. Αν καταλάβεις το ThreadPool, καταλαβαίνεις γιατί ο async κώδικας κάνει scale, γιατί οι blocking κλήσεις πληγώνουν τόσο πολύ έναν web server και πότε πραγματικά έχει νόημα να φτιάξεις δικό σου thread. Αυτό το άρθρο ξεκινά από το κόστος ενός thread, χτίζει πάνω σε αυτό για να δείξει τι κάνει το pool για αυτό το κόστος και μετά ακολουθεί το pool μέσα από το Task.Run, το LongRunning, το async/await και το ASP.NET Core. Αν δεν είσαι ακόμα σίγουρος τι είναι ένα thread ή πώς διαφέρει από ένα Task, ξεκίνα από το προηγούμενο άρθρο, Threads και Tasks στο .NET.

What does a thread actually cost?

Πόσο κοστίζει στην πραγματικότητα ένα thread;

A thread is not a cheap object like a List or a string. It is an operating system resource. When you write new Thread(...) and call Start(), several expensive things happen behind the scenes:

  • A kernel object is created. The OS has to allocate and track the thread, which means a call into the kernel, not just a managed allocation.
  • A stack is reserved. Every thread gets its own stack, typically around 1 MB of reserved address space by default. A thousand threads means roughly a gigabyte of reserved address space just for stacks.
  • The runtime has to set it up. The CLR creates its own bookkeeping for the thread, and libraries that keep per-thread state get notified that a new thread exists.
  • Context switching gets more expensive. The CPU has a limited number of cores. If you have 8 cores and 500 runnable threads, the OS spends a growing share of its time saving and restoring thread state instead of running your code.
  • Destroying it costs too. When the thread ends, all of the above has to be torn down again.

If the work you want to run takes a few microseconds, creating and destroying a whole thread for it can easily cost more than the work itself. The following snippet runs the same tiny piece of work a thousand times, first with a brand-new thread each time, then by handing it to the ThreadPool:

Ένα thread δεν είναι ένα φθηνό αντικείμενο σαν μια List ή ένα string. Είναι πόρος του λειτουργικού συστήματος. Όταν γράφεις new Thread(...) και καλείς Start(), συμβαίνουν πίσω από τις κουρτίνες αρκετά ακριβά πράγματα:

  • Δημιουργείται ένα kernel object. Το λειτουργικό πρέπει να δεσμεύσει και να παρακολουθεί το thread, που σημαίνει κλήση στον kernel, όχι απλώς ένα managed allocation.
  • Δεσμεύεται ένα stack. Κάθε thread παίρνει το δικό του stack, συνήθως γύρω στο 1 MB δεσμευμένου address space από προεπιλογή. Χίλια threads σημαίνει περίπου ένα gigabyte δεσμευμένου address space μόνο για stacks.
  • Το runtime πρέπει να το στήσει. Το CLR φτιάχνει τη δική του εσωτερική καταγραφή για το thread, και οι βιβλιοθήκες που κρατούν per-thread state ενημερώνονται ότι υπάρχει νέο thread.
  • Το context switching γίνεται πιο ακριβό. Η CPU έχει περιορισμένο αριθμό πυρήνων. Αν έχεις 8 πυρήνες και 500 threads που θέλουν να τρέξουν, το λειτουργικό ξοδεύει όλο και μεγαλύτερο μέρος του χρόνου του σώζοντας και επαναφέροντας την κατάσταση των threads αντί να τρέχει τον κώδικά σου.
  • Και η καταστροφή του κοστίζει. Όταν το thread τελειώσει, όλα τα παραπάνω πρέπει να γκρεμιστούν ξανά.

Αν η δουλειά που θέλεις να τρέξεις κρατά λίγα microseconds, η δημιουργία και καταστροφή ενός ολόκληρου thread γι' αυτήν μπορεί εύκολα να κοστίσει περισσότερο από την ίδια τη δουλειά. Το παρακάτω snippet τρέχει την ίδια μικρή δουλειά χίλιες φορές, πρώτα με ένα ολοκαίνουριο thread κάθε φορά και μετά δίνοντάς τη στο ThreadPool:

using System.Diagnostics;

var sw = Stopwatch.StartNew();
var threads = new List<Thread>();
for (int i = 0; i < 1000; i++)
{
    var thread = new Thread(() => DoTinyWork());
    thread.Start();
    threads.Add(thread);
}
foreach (var thread in threads) thread.Join();
Console.WriteLine($"new Thread x1000: {sw.ElapsedMilliseconds} ms");

sw.Restart();
using var done = new CountdownEvent(1000);
for (int i = 0; i < 1000; i++)
{
    ThreadPool.QueueUserWorkItem(state =>
    {
        DoTinyWork();
        done.Signal();
    });
}
done.Wait();
Console.WriteLine($"ThreadPool x1000: {sw.ElapsedMilliseconds} ms");

static void DoTinyWork() => Thread.SpinWait(1000);

The exact numbers depend on your machine, but the ThreadPool version is consistently many times faster. The work is identical. The difference is entirely the cost of creating and destroying a thousand threads versus reusing a handful.

Τα ακριβή νούμερα εξαρτώνται από το μηχάνημά σου, αλλά η έκδοση με το ThreadPool είναι σταθερά πολλές φορές πιο γρήγορη. Η δουλειά είναι ακριβώς η ίδια. Η διαφορά είναι εξ ολοκλήρου το κόστος δημιουργίας και καταστροφής χιλίων threads έναντι της επαναχρησιμοποίησης λίγων.

What is the ThreadPool?

Τι είναι το ThreadPool;

The ThreadPool is a set of worker threads that the .NET runtime creates once and keeps alive for the lifetime of the process. Instead of creating a thread per piece of work, you put the work into a queue. A free pool thread picks it up, runs it and, when it finishes, does not die. It goes back and picks up the next item from the queue. The threads are the expensive part, so the pool pays for them once and reuses them thousands of times.

Think of a restaurant. Hiring a new waiter for every customer who walks in, then firing them after the meal, would be absurd. The hiring paperwork would take longer than serving the table. Instead the restaurant has a fixed team of waiters. Orders go into a queue, and whichever waiter is free takes the next one. If the restaurant gets consistently busier, the manager hires a few more, carefully, because too many waiters bumping into each other in a small room slows everyone down. That manager is the ThreadPool.

A few details about how the pool is organized under the hood:

  • A global queue. Work queued from a non-pool thread, for example from your Main method, goes into a shared global queue that every pool thread can take from.
  • Local queues per thread. Each pool thread also has its own local queue. When code already running on a pool thread queues more work, for example a Task.Run inside another Task.Run, that work goes to the current thread's local queue first. This is faster because there is less contention and the data the work needs is probably still in that core's cache.
  • Work stealing. When a pool thread's own local queue is empty and the global queue is empty too, it steals work from the end of another thread's local queue instead of sitting idle.
  • Worker threads and I/O completion threads. The pool tracks two kinds of threads: worker threads, which run your code, and I/O completion threads, which react when the operating system reports that an I/O operation has finished. You will see both numbers when you query the pool.

Το ThreadPool είναι ένα σύνολο από worker threads που το .NET runtime δημιουργεί μία φορά και κρατά ζωντανά για όλη τη διάρκεια ζωής του process. Αντί να φτιάχνεις ένα thread για κάθε κομμάτι δουλειάς, βάζεις τη δουλειά σε μια ουρά. Ένα ελεύθερο thread του pool την παίρνει, την τρέχει και, όταν τελειώσει, δεν πεθαίνει. Γυρίζει πίσω και παίρνει το επόμενο αντικείμενο από την ουρά. Τα threads είναι το ακριβό κομμάτι, οπότε το pool τα πληρώνει μία φορά και τα επαναχρησιμοποιεί χιλιάδες φορές.

Σκέψου ένα εστιατόριο. Το να προσλαμβάνεις έναν καινούριο σερβιτόρο για κάθε πελάτη που μπαίνει και να τον απολύεις μετά το φαγητό θα ήταν παράλογο. Τα χαρτιά της πρόσληψης θα έπαιρναν περισσότερο χρόνο από το σερβίρισμα του τραπεζιού. Αντί γι' αυτό, το εστιατόριο έχει μια σταθερή ομάδα σερβιτόρων. Οι παραγγελίες μπαίνουν σε μια ουρά και όποιος σερβιτόρος είναι ελεύθερος παίρνει την επόμενη. Αν το εστιατόριο έχει σταθερά περισσότερη κίνηση, ο manager προσλαμβάνει μερικούς ακόμα, προσεκτικά, γιατί πάρα πολλοί σερβιτόροι που σκοντάφτουν ο ένας στον άλλο σε ένα μικρό χώρο καθυστερούν όλους. Αυτός ο manager είναι το ThreadPool.

Μερικές λεπτομέρειες για το πώς είναι οργανωμένο το pool εσωτερικά:

  • Μια global ουρά. Δουλειά που μπαίνει στην ουρά από thread που δεν ανήκει στο pool, για παράδειγμα από τη μέθοδο Main, πηγαίνει σε μια κοινή global ουρά από την οποία μπορεί να πάρει κάθε thread του pool.
  • Τοπικές ουρές ανά thread. Κάθε thread του pool έχει επίσης τη δική του τοπική ουρά. Όταν κώδικας που ήδη τρέχει σε thread του pool βάζει κι άλλη δουλειά στην ουρά, για παράδειγμα ένα Task.Run μέσα σε άλλο Task.Run, αυτή η δουλειά πηγαίνει πρώτα στην τοπική ουρά του τρέχοντος thread. Αυτό είναι πιο γρήγορο γιατί υπάρχει λιγότερο contention και τα δεδομένα που χρειάζεται η δουλειά είναι πιθανότατα ακόμα στην cache εκείνου του πυρήνα.
  • Work stealing. Όταν η τοπική ουρά ενός thread του pool είναι άδεια και η global ουρά είναι επίσης άδεια, το thread κλέβει δουλειά από το τέλος της τοπικής ουράς ενός άλλου thread αντί να κάθεται αδρανές.
  • Worker threads και I/O completion threads. Το pool παρακολουθεί δύο είδη threads: τα worker threads, που τρέχουν τον κώδικά σου, και τα I/O completion threads, που αντιδρούν όταν το λειτουργικό αναφέρει ότι μια λειτουργία I/O τελείωσε. Θα δεις και τους δύο αριθμούς όταν ρωτήσεις το pool.

Seeing the reuse with your own eyes

Βλέποντας την επαναχρησιμοποίηση με τα μάτια σου

Queue 100 work items and record which thread ran each one. If the pool created a thread per item you would see 100 distinct thread ids. You will not:

Βάλε 100 work items στην ουρά και κατέγραψε ποιο thread έτρεξε το καθένα. Αν το pool έφτιαχνε ένα thread για κάθε item θα έβλεπες 100 διαφορετικά thread ids. Δεν θα τα δεις:

using System.Collections.Concurrent;

var ids = new ConcurrentDictionary<int, int>();
using var done = new CountdownEvent(100);

for (int i = 0; i < 100; i++)
{
    ThreadPool.QueueUserWorkItem(state =>
    {
        ids.AddOrUpdate(Environment.CurrentManagedThreadId, 1, (_, count) => count + 1);
        Thread.Sleep(10);
        done.Signal();
    });
}

done.Wait();
Console.WriteLine($"100 work items ran on {ids.Count} distinct threads");
foreach (var (id, count) in ids.OrderBy(pair => pair.Key))
{
    Console.WriteLine($"  thread {id}: {count} items");
}

On a typical machine, 100 items run on roughly as many threads as you have CPU cores, maybe a few more, with each thread handling a dozen or more items. Same threads, over and over.

Σε ένα τυπικό μηχάνημα, τα 100 items τρέχουν σε περίπου τόσα threads όσοι είναι οι πυρήνες της CPU σου, ίσως λίγα παραπάνω, με κάθε thread να αναλαμβάνει δέκα ή περισσότερα items. Τα ίδια threads, ξανά και ξανά.

How many threads does the pool have?

Πόσα threads έχει το pool;

The pool is not a fixed size. It starts small and grows or shrinks based on demand. You can ask it what it is working with:

Το pool δεν έχει σταθερό μέγεθος. Ξεκινά μικρό και μεγαλώνει ή μικραίνει ανάλογα με τη ζήτηση. Μπορείς να το ρωτήσεις με τι δουλεύει:

ThreadPool.GetMinThreads(out int minWorker, out int minIo);
ThreadPool.GetMaxThreads(out int maxWorker, out int maxIo);

Console.WriteLine($"Processors:      {Environment.ProcessorCount}");
Console.WriteLine($"Min worker / IO: {minWorker} / {minIo}");
Console.WriteLine($"Max worker / IO: {maxWorker} / {maxIo}");
Console.WriteLine($"Threads now:     {ThreadPool.ThreadCount}");
Console.WriteLine($"Pending items:   {ThreadPool.PendingWorkItemCount}");

The important number is the minimum, which by default equals the number of CPU cores. Here is how the pool behaves around it:

  • Up to the minimum, the pool creates a new thread immediately whenever work arrives and no thread is free.
  • Above the minimum, the pool becomes cautious. It does not create a new thread the instant the queue is non-empty. It uses a hill-climbing algorithm that adds a thread, measures whether throughput actually improved and backs off if it did not. If work sits in the queue and no thread finishes, it also injects threads gradually, with a delay between each one, to avoid starvation.
  • Idle threads above the minimum are eventually retired, so the pool shrinks back when the load drops.

That cautious growth is deliberate. More threads than cores does not mean more CPU work gets done, it just means more context switching. The pool's whole strategy assumes that work items are short and that threads come back quickly. Keep that assumption in mind, because the rest of this article is about what happens when your code respects it and what happens when it does not.

Ο σημαντικός αριθμός είναι το minimum, που από προεπιλογή ισούται με τον αριθμό των πυρήνων της CPU. Δες πώς συμπεριφέρεται το pool γύρω από αυτόν:

  • Μέχρι το minimum, το pool φτιάχνει αμέσως νέο thread κάθε φορά που φτάνει δουλειά και κανένα thread δεν είναι ελεύθερο.
  • Πάνω από το minimum, το pool γίνεται προσεκτικό. Δεν φτιάχνει νέο thread τη στιγμή που η ουρά δεν είναι άδεια. Χρησιμοποιεί έναν αλγόριθμο hill-climbing που προσθέτει ένα thread, μετρά αν το throughput πράγματι βελτιώθηκε και κάνει πίσω αν δεν βελτιώθηκε. Αν η δουλειά κάθεται στην ουρά και κανένα thread δεν τελειώνει, προσθέτει επίσης threads σταδιακά, με καθυστέρηση ανάμεσα στο καθένα, για να αποφύγει το starvation.
  • Τα αδρανή threads πάνω από το minimum τελικά αποσύρονται, οπότε το pool μικραίνει ξανά όταν πέσει το φορτίο.

Αυτή η προσεκτική ανάπτυξη είναι σκόπιμη. Περισσότερα threads από πυρήνες δεν σημαίνει ότι γίνεται περισσότερη δουλειά CPU, σημαίνει απλώς περισσότερο context switching. Όλη η στρατηγική του pool υποθέτει ότι τα work items είναι σύντομα και ότι τα threads επιστρέφουν γρήγορα. Κράτα αυτή την υπόθεση στο μυαλό σου, γιατί το υπόλοιπο άρθρο αφορά το τι συμβαίνει όταν ο κώδικάς σου τη σέβεται και τι συμβαίνει όταν δεν τη σέβεται.

Task.Run: the ThreadPool with a nicer API

Task.Run: το ThreadPool με πιο ωραίο API

You rarely call ThreadPool.QueueUserWorkItem directly in modern code. You call Task.Run. It does exactly the same thing underneath, queues your delegate to the pool, but it gives you back a Task you can await, get a result from, observe exceptions on and cancel.

Σπάνια καλείς απευθείας το ThreadPool.QueueUserWorkItem σε σύγχρονο κώδικα. Καλείς το Task.Run. Κάνει ακριβώς το ίδιο πράγμα από κάτω, βάζει το delegate σου στην ουρά του pool, αλλά σου επιστρέφει ένα Task στο οποίο μπορείς να κάνεις await, να πάρεις αποτέλεσμα, να δεις exceptions και να κάνεις cancel.

Console.WriteLine($"Main:     thread {Environment.CurrentManagedThreadId}, " +
                  $"pool? {Thread.CurrentThread.IsThreadPoolThread}");

Task<int> task = Task.Run(() =>
{
    Console.WriteLine($"Task.Run: thread {Environment.CurrentManagedThreadId}, " +
                      $"pool? {Thread.CurrentThread.IsThreadPoolThread}");

    // CPU-bound work
    return Enumerable.Range(1, 1_000_000).Sum(x => x % 7);
});

int result = await task;
Console.WriteLine($"Result: {result}");

The output shows pool? False for Main and pool? True inside Task.Run, on a different thread id. Here is the path your delegate takes, simplified:

Το output δείχνει pool? False για το Main και pool? True μέσα στο Task.Run, σε διαφορετικό thread id. Αυτή είναι η διαδρομή που ακολουθεί το delegate σου, απλοποιημένα:

Task.Run(work)
  -> Task.Factory.StartNew(work, CancellationToken.None,
         TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)
  -> TaskScheduler.Default is the ThreadPoolTaskScheduler
  -> ThreadPoolTaskScheduler.QueueTask(task)
  -> the Task object itself is queued to the ThreadPool as a work item
  -> a free pool thread dequeues it and runs your delegate

So a Task is not a thread. A Task is an object that represents a piece of work and its eventual result. The ThreadPool is what actually provides a thread to run it. This distinction matters a lot once we get to async/await, where a Task can exist for seconds without any thread working on it at all.

Task.Run is the right tool for CPU-bound work you want off the current thread, for example keeping a desktop UI responsive while you resize a batch of images. It is the wrong tool for making I/O "async", which we will come back to in the ASP.NET Core section.

Άρα ένα Task δεν είναι thread. Ένα Task είναι ένα αντικείμενο που αναπαριστά ένα κομμάτι δουλειάς και το τελικό του αποτέλεσμα. Το ThreadPool είναι αυτό που πραγματικά παρέχει ένα thread για να το τρέξει. Αυτή η διάκριση μετράει πολύ μόλις φτάσουμε στο async/await, όπου ένα Task μπορεί να υπάρχει για δευτερόλεπτα χωρίς κανένα thread να δουλεύει πάνω του.

Το Task.Run είναι το σωστό εργαλείο για CPU-bound δουλειά που θέλεις να βγάλεις από το τρέχον thread, για παράδειγμα για να μένει responsive ένα desktop UI ενώ αλλάζεις μέγεθος σε μια σειρά από εικόνες. Είναι λάθος εργαλείο για να κάνεις το I/O "async", κάτι στο οποίο θα επιστρέψουμε στο κομμάτι για το ASP.NET Core.

LongRunning: when the work should not borrow a pool thread

LongRunning: όταν η δουλειά δεν πρέπει να δανειστεί thread του pool

Remember the pool's assumption: work items are short and threads come back quickly. Now imagine a background loop that reads messages from a queue for the entire lifetime of the app, blocking while it waits. If you start it with Task.Run, it takes a pool thread and never gives it back. Do that a few times and you have quietly removed several threads from the pool permanently. Every other piece of work in the process now competes for fewer threads.

For this case, Task.Factory.StartNew accepts TaskCreationOptions.LongRunning. This option is a hint to the scheduler, and the default ThreadPoolTaskScheduler honors it in a very concrete way: instead of queuing the task to the pool, it creates a brand-new dedicated background thread just for this task.

Θυμήσου την υπόθεση του pool: τα work items είναι σύντομα και τα threads επιστρέφουν γρήγορα. Τώρα φαντάσου ένα background loop που διαβάζει μηνύματα από μια ουρά για όλη τη διάρκεια ζωής της εφαρμογής, κάνοντας block όσο περιμένει. Αν το ξεκινήσεις με Task.Run, παίρνει ένα thread του pool και δεν το επιστρέφει ποτέ. Κάν' το αυτό μερικές φορές και έχεις αφαιρέσει αθόρυβα αρκετά threads από το pool μόνιμα. Κάθε άλλο κομμάτι δουλειάς στο process ανταγωνίζεται πλέον για λιγότερα threads.

Γι' αυτή την περίπτωση, το Task.Factory.StartNew δέχεται το TaskCreationOptions.LongRunning. Αυτή η επιλογή είναι ένα hint προς τον scheduler, και ο default ThreadPoolTaskScheduler το τιμά με πολύ συγκεκριμένο τρόπο: αντί να βάλει το task στην ουρά του pool, φτιάχνει ένα ολοκαίνουριο αφιερωμένο background thread μόνο για αυτό το task.

using var cts = new CancellationTokenSource();

Task consumer = Task.Factory.StartNew(() =>
{
    Console.WriteLine($"LongRunning: thread {Environment.CurrentManagedThreadId}, " +
                      $"pool? {Thread.CurrentThread.IsThreadPoolThread}");

    while (!cts.Token.IsCancellationRequested)
    {
        ProcessNextMessage(); // blocking, runs for the lifetime of the app
    }
},
cts.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);

This prints pool? False. The task still looks and behaves like any other Task, you can await it and observe its exceptions, but the thread underneath is its own. The pool keeps all its threads for the short work it was designed for.

A few rules around LongRunning:

  • Task.Run does not take TaskCreationOptions. To use LongRunning you need Task.Factory.StartNew, and you should pass TaskScheduler.Default explicitly so it does not accidentally pick up some other ambient scheduler.
  • Use it only for work that really runs for a long time, think seconds to the whole app lifetime, and that blocks or burns CPU synchronously. Using it for short work brings back exactly the thread creation cost the pool exists to avoid.
  • It is pointless with an async delegate. This is the classic mistake:

Αυτό τυπώνει pool? False. Το task εξακολουθεί να μοιάζει και να συμπεριφέρεται όπως κάθε άλλο Task, μπορείς να κάνεις await και να δεις τα exceptions του, αλλά το thread από κάτω είναι δικό του. Το pool κρατά όλα τα threads του για τη σύντομη δουλειά για την οποία σχεδιάστηκε.

Μερικοί κανόνες γύρω από το LongRunning:

  • Το Task.Run δεν δέχεται TaskCreationOptions. Για να χρησιμοποιήσεις το LongRunning χρειάζεσαι το Task.Factory.StartNew, και καλό είναι να περνάς ρητά το TaskScheduler.Default για να μην πάρει κατά λάθος κάποιον άλλο scheduler από το περιβάλλον.
  • Χρησιμοποίησέ το μόνο για δουλειά που πραγματικά τρέχει για πολύ, από δευτερόλεπτα μέχρι όλη τη ζωή της εφαρμογής, και που κάνει block ή καίει CPU συγχρονισμένα. Αν το χρησιμοποιήσεις για σύντομη δουλειά, φέρνεις πίσω ακριβώς το κόστος δημιουργίας thread που το pool υπάρχει για να αποφύγει.
  • Δεν έχει νόημα με async delegate. Αυτό είναι το κλασικό λάθος:
// Looks dedicated. Is not, after the first await.
Task.Factory.StartNew(async () =>
{
    while (true)
    {
        await Task.Delay(1000); // the dedicated thread exits here
        DoWork();               // this runs on a pool thread
    }
}, TaskCreationOptions.LongRunning);

The dedicated thread only runs the delegate up to the first await that actually waits. At that point the method returns, the dedicated thread has nothing left to do and ends, and everything after the await resumes on the ThreadPool like any other async code. You paid for a new thread and used it for a few microseconds. On top of that, StartNew with an async lambda returns a Task<Task>, so awaiting the outer task does not wait for the loop. If your background work is async, skip LongRunning entirely and just call the async method. That is the next section.

Το αφιερωμένο thread τρέχει το delegate μόνο μέχρι το πρώτο await που πραγματικά περιμένει. Σε εκείνο το σημείο η μέθοδος επιστρέφει, το αφιερωμένο thread δεν έχει τίποτα άλλο να κάνει και τερματίζει, και ό,τι υπάρχει μετά το await συνεχίζει στο ThreadPool όπως κάθε άλλος async κώδικας. Πλήρωσες για ένα νέο thread και το χρησιμοποίησες για λίγα microseconds. Επιπλέον, το StartNew με async lambda επιστρέφει Task<Task>, οπότε το await στο εξωτερικό task δεν περιμένει το loop. Αν η background δουλειά σου είναι async, παράλειψε εντελώς το LongRunning και απλώς κάλεσε την async μέθοδο. Αυτό είναι το επόμενο κομμάτι.

async/await: giving the thread back during I/O

async/await: επιστροφή του thread κατά τη διάρκεια του I/O

Most of what a typical backend does is not CPU work. It is waiting. Waiting for a database query, waiting for an HTTP call to another service, waiting for a file to be read. During that wait the CPU has nothing to do for this request. The question is: what is the thread doing in the meantime?

With synchronous code, the answer is "nothing, but it is still taken". The thread sits blocked inside the call, holding its stack and its slot in the pool, unable to serve anyone else. With async/await, the answer is "it went back to the pool to do other work".

Back to the restaurant. A synchronous waiter takes an order to the kitchen and then stands at the kitchen door until the food is ready, ignoring every other table. An asynchronous waiter hands the order to the kitchen and goes to serve other tables. When the kitchen rings the bell, whichever waiter is free carries the plate out. It may not be the same waiter who took the order, and the customer does not care. That last detail is exactly what you see in code:

Το μεγαλύτερο μέρος αυτού που κάνει ένα τυπικό backend δεν είναι δουλειά CPU. Είναι αναμονή. Αναμονή για ένα query στη βάση, αναμονή για μια HTTP κλήση σε άλλο service, αναμονή για να διαβαστεί ένα αρχείο. Κατά τη διάρκεια αυτής της αναμονής η CPU δεν έχει τίποτα να κάνει για αυτό το request. Το ερώτημα είναι: τι κάνει το thread στο μεταξύ;

Με synchronous κώδικα, η απάντηση είναι "τίποτα, αλλά παραμένει πιασμένο". Το thread κάθεται blocked μέσα στην κλήση, κρατώντας το stack του και τη θέση του στο pool, χωρίς να μπορεί να εξυπηρετήσει κανέναν άλλο. Με async/await, η απάντηση είναι "γύρισε πίσω στο pool να κάνει άλλη δουλειά".

Πίσω στο εστιατόριο. Ένας synchronous σερβιτόρος πηγαίνει την παραγγελία στην κουζίνα και μετά στέκεται στην πόρτα της κουζίνας μέχρι να ετοιμαστεί το φαγητό, αγνοώντας κάθε άλλο τραπέζι. Ένας asynchronous σερβιτόρος δίνει την παραγγελία στην κουζίνα και πηγαίνει να εξυπηρετήσει άλλα τραπέζια. Όταν η κουζίνα χτυπήσει το κουδούνι, όποιος σερβιτόρος είναι ελεύθερος φέρνει το πιάτο. Μπορεί να μην είναι ο ίδιος σερβιτόρος που πήρε την παραγγελία, και ο πελάτης δεν νοιάζεται. Αυτή η τελευταία λεπτομέρεια είναι ακριβώς αυτό που βλέπεις στον κώδικα:

using var http = new HttpClient();

Console.WriteLine($"Before await: thread {Environment.CurrentManagedThreadId}");

string html = await http.GetStringAsync("https://example.com");

Console.WriteLine($"After await:  thread {Environment.CurrentManagedThreadId}");
Console.WriteLine($"Downloaded {html.Length} characters");

In a console app the thread id after the await is very often different from the one before it. Here is what happens step by step:

  1. GetStringAsync starts the network request. The actual sending and receiving is handed to the operating system's networking stack.
  2. The request has not completed yet, so GetStringAsync returns an incomplete Task<string>.
  3. await sees the task is incomplete. The compiler-generated state machine registers "the rest of this method" as a continuation on that task, then returns from the method.
  4. The thread is now free. If it is a pool thread, it goes straight back to the pool and picks up other work. While the network round trip is in flight, no thread at all is blocked waiting for it. The OS and the network card are doing the waiting.
  5. When the response arrives, the OS signals completion. The runtime completes the Task, and its continuation is queued to the ThreadPool.
  6. Any free pool thread picks up the continuation and runs the code after the await. That is why the thread id can change.

This is the whole reason async scales. A server with 50 pool threads that each block for 200 ms on a database call can handle about 250 requests per second. The same server with async code can have thousands of requests waiting on the database at once, because waiting does not hold a thread. The threads are only used for the short bursts of real work between awaits, which is exactly the kind of work the pool is designed for.

Two small examples show the difference between blocking and releasing:

Σε μια console εφαρμογή το thread id μετά το await είναι πολύ συχνά διαφορετικό από αυτό πριν. Δες τι συμβαίνει βήμα βήμα:

  1. Το GetStringAsync ξεκινά το network request. Η πραγματική αποστολή και λήψη παραδίδεται στο networking stack του λειτουργικού συστήματος.
  2. Το request δεν έχει ολοκληρωθεί ακόμα, οπότε το GetStringAsync επιστρέφει ένα μη ολοκληρωμένο Task<string>.
  3. Το await βλέπει ότι το task δεν έχει ολοκληρωθεί. Το state machine που φτιάχνει ο compiler καταχωρεί "το υπόλοιπο αυτής της μεθόδου" ως continuation πάνω σε εκείνο το task και μετά επιστρέφει από τη μέθοδο.
  4. Το thread είναι πλέον ελεύθερο. Αν είναι thread του pool, γυρίζει κατευθείαν πίσω στο pool και παίρνει άλλη δουλειά. Όσο το network round trip βρίσκεται σε εξέλιξη, κανένα απολύτως thread δεν είναι blocked περιμένοντάς το. Την αναμονή την κάνουν το λειτουργικό και η κάρτα δικτύου.
  5. Όταν φτάσει η απάντηση, το λειτουργικό σηματοδοτεί την ολοκλήρωση. Το runtime ολοκληρώνει το Task, και το continuation του μπαίνει στην ουρά του ThreadPool.
  6. Οποιοδήποτε ελεύθερο thread του pool παίρνει το continuation και τρέχει τον κώδικα μετά το await. Γι' αυτό μπορεί να αλλάξει το thread id.

Αυτός είναι ολόκληρος ο λόγος που το async κάνει scale. Ένας server με 50 threads στο pool που το καθένα κάνει block για 200 ms σε μια κλήση στη βάση μπορεί να εξυπηρετήσει περίπου 250 requests το δευτερόλεπτο. Ο ίδιος server με async κώδικα μπορεί να έχει χιλιάδες requests να περιμένουν τη βάση ταυτόχρονα, γιατί η αναμονή δεν κρατά thread. Τα threads χρησιμοποιούνται μόνο για τα σύντομα κομμάτια πραγματικής δουλειάς ανάμεσα στα awaits, που είναι ακριβώς το είδος δουλειάς για το οποίο είναι σχεδιασμένο το pool.

Δύο μικρά παραδείγματα δείχνουν τη διαφορά ανάμεσα στο να κάνεις block και στο να απελευθερώνεις:

// Blocks: the thread is held for the full second, doing nothing
Thread.Sleep(1000);

// Releases: no thread is held during the second
await Task.Delay(1000);

// Blocks: sync-over-async, the worst of both worlds
string blockingBody = http.GetStringAsync(url).Result;

// Releases
string asyncBody = await http.GetStringAsync(url);

Note that async by itself does not create threads and does not make anything run in parallel. It only gives the thread back while something else, the network, the disk, a timer, does the waiting. For CPU-bound work there is nothing to wait for, so there is nothing to release. That is where Task.Run comes in, not async.

Πρόσεξε ότι το async από μόνο του δεν φτιάχνει threads και δεν κάνει τίποτα να τρέξει παράλληλα. Απλώς επιστρέφει το thread όσο κάτι άλλο, το δίκτυο, ο δίσκος, ένας timer, κάνει την αναμονή. Για CPU-bound δουλειά δεν υπάρχει τίποτα να περιμένεις, οπότε δεν υπάρχει τίποτα να απελευθερώσεις. Εκεί μπαίνει το Task.Run, όχι το async.

How ASP.NET Core uses the ThreadPool

Πώς χρησιμοποιεί το ASP.NET Core το ThreadPool

ASP.NET Core does not create a thread per request. Kestrel, the built-in web server, accepts connections and reads incoming data using async I/O. When a full request has arrived, it is processed on a ThreadPool thread: middleware, routing, model binding, your controller or minimal API handler, all of it. When your handler hits an await on real I/O, that pool thread goes back to the pool and starts processing some other request. When the I/O completes, the rest of your handler continues on whichever pool thread is free.

There is also no SynchronizationContext in ASP.NET Core, unlike classic ASP.NET or WPF. Continuations are not forced back onto a specific thread, they simply run on any pool thread. This is also why ConfigureAwait(false) makes no practical difference inside ASP.NET Core application code.

Compare two endpoints that both take two seconds to respond:

Το ASP.NET Core δεν φτιάχνει ένα thread ανά request. Ο Kestrel, ο ενσωματωμένος web server, δέχεται συνδέσεις και διαβάζει τα εισερχόμενα δεδομένα με async I/O. Όταν φτάσει ένα ολόκληρο request, επεξεργάζεται σε ένα thread του ThreadPool: middleware, routing, model binding, ο controller σου ή ο minimal API handler, όλα. Όταν ο handler σου φτάσει σε ένα await πάνω σε πραγματικό I/O, αυτό το thread του pool γυρίζει στο pool και αρχίζει να επεξεργάζεται κάποιο άλλο request. Όταν ολοκληρωθεί το I/O, ο υπόλοιπος handler συνεχίζει σε όποιο thread του pool είναι ελεύθερο.

Επίσης δεν υπάρχει SynchronizationContext στο ASP.NET Core, σε αντίθεση με το κλασικό ASP.NET ή το WPF. Τα continuations δεν αναγκάζονται να επιστρέψουν σε συγκεκριμένο thread, απλώς τρέχουν σε οποιοδήποτε thread του pool. Γι' αυτό και το ConfigureAwait(false) δεν κάνει πρακτικά καμία διαφορά μέσα σε κώδικα εφαρμογής ASP.NET Core.

Σύγκρινε δύο endpoints που και τα δύο κάνουν δύο δευτερόλεπτα να απαντήσουν:

var app = WebApplication.Create(args);

// Holds a pool thread for the full 2 seconds
app.MapGet("/blocking", () =>
{
    Thread.Sleep(2000);
    return "done";
});

// Holds a pool thread for a few microseconds before and after
app.MapGet("/async", async () =>
{
    await Task.Delay(2000);
    return "done";
});

// Sync-over-async: looks async, behaves like /blocking
app.MapGet("/sync-over-async", () =>
{
    Task.Delay(2000).Wait();
    return "done";
});

app.Run();

Hit each endpoint with a load tool sending a few hundred concurrent requests and watch what happens:

  • /async answers every request in about two seconds. While they all wait, almost no pool threads are in use. The pool barely grows.
  • /blocking and /sync-over-async start fine, then fall apart. Every request holds a pool thread for two full seconds. Once all threads are busy, new requests sit in the queue. The pool notices and starts adding threads, but above the minimum it adds them gradually, not hundreds at once. Response times climb from two seconds to ten, twenty, thirty. And the CPU is nearly idle the whole time, because the threads are not working, they are just blocked.

This is called ThreadPool starvation, and it is one of the most common performance problems in real ASP.NET Core apps. The classic signature is high latency, a growing thread count and low CPU usage at the same time. The usual causes are .Result, .Wait() or .GetAwaiter().GetResult() on async calls, Thread.Sleep in request code and synchronous database or file APIs used where async ones exist. The fix is to go async all the way down, not to raise the minimum thread count. Calling ThreadPool.SetMinThreads can hide the symptom for a while, but the threads are still being wasted.

One more trap: wrapping blocking code in Task.Run inside a controller does not help.

Χτύπησε κάθε endpoint με ένα εργαλείο load testing που στέλνει μερικές εκατοντάδες ταυτόχρονα requests και δες τι συμβαίνει:

  • Το /async απαντά σε κάθε request σε περίπου δύο δευτερόλεπτα. Όσο όλα περιμένουν, σχεδόν κανένα thread του pool δεν είναι σε χρήση. Το pool μόλις που μεγαλώνει.
  • Το /blocking και το /sync-over-async ξεκινούν καλά και μετά καταρρέουν. Κάθε request κρατά ένα thread του pool για δύο ολόκληρα δευτερόλεπτα. Μόλις όλα τα threads είναι απασχολημένα, τα νέα requests κάθονται στην ουρά. Το pool το καταλαβαίνει και αρχίζει να προσθέτει threads, αλλά πάνω από το minimum τα προσθέτει σταδιακά, όχι εκατοντάδες μαζί. Οι χρόνοι απόκρισης ανεβαίνουν από δύο δευτερόλεπτα σε δέκα, είκοσι, τριάντα. Και η CPU είναι σχεδόν αδρανής όλη την ώρα, γιατί τα threads δεν δουλεύουν, απλώς είναι blocked.

Αυτό λέγεται ThreadPool starvation και είναι ένα από τα πιο συνηθισμένα προβλήματα απόδοσης σε πραγματικές εφαρμογές ASP.NET Core. Η κλασική υπογραφή είναι υψηλό latency, αριθμός threads που μεγαλώνει και χαμηλή χρήση CPU ταυτόχρονα. Οι συνηθισμένες αιτίες είναι .Result, .Wait() ή .GetAwaiter().GetResult() σε async κλήσεις, Thread.Sleep μέσα σε κώδικα request και synchronous APIs για βάση ή αρχεία εκεί που υπάρχουν async εκδόσεις. Η λύση είναι να γίνει ο κώδικας async μέχρι κάτω, όχι να ανεβάσεις τον ελάχιστο αριθμό threads. Η κλήση ThreadPool.SetMinThreads μπορεί να κρύψει το σύμπτωμα για λίγο, αλλά τα threads εξακολουθούν να σπαταλιούνται.

Μια ακόμα παγίδα: το να τυλίξεις blocking κώδικα σε Task.Run μέσα σε έναν controller δεν βοηθά.

// Fake async: frees one pool thread by blocking another one
[HttpGet]
public async Task<IActionResult> GetReport()
{
    var report = await Task.Run(() => _repository.LoadReportSync());
    return Ok(report);
}

// Real async: no thread is held while the database works
[HttpGet]
public async Task<IActionResult> GetReport()
{
    var report = await _repository.LoadReportAsync();
    return Ok(report);
}

In the first version the request thread is released, but only because another pool thread is now blocked inside LoadReportSync. You moved the problem from one pool thread to another and added the overhead of a hop between them. In a desktop app, Task.Run is useful because it moves work off the UI thread, which is special. In ASP.NET Core every request is already on a pool thread, there is no special thread to protect, so Task.Run around blocking I/O buys you nothing.

Στην πρώτη έκδοση το thread του request απελευθερώνεται, αλλά μόνο επειδή ένα άλλο thread του pool είναι τώρα blocked μέσα στο LoadReportSync. Μετέφερες το πρόβλημα από ένα thread του pool σε ένα άλλο και πρόσθεσες και το κόστος της μετάβασης ανάμεσά τους. Σε μια desktop εφαρμογή το Task.Run είναι χρήσιμο γιατί βγάζει τη δουλειά από το UI thread, που είναι ειδικό. Στο ASP.NET Core κάθε request είναι ήδη σε thread του pool, δεν υπάρχει κάποιο ειδικό thread να προστατέψεις, οπότε το Task.Run γύρω από blocking I/O δεν σου προσφέρει τίποτα.

Who else uses the ThreadPool?

Ποιος άλλος χρησιμοποιεί το ThreadPool;

Once you know to look for it, the pool is everywhere. Parallel.For, Parallel.ForEach and PLINQ split their work into chunks and run them on pool threads. System.Threading.Timer and System.Timers.Timer fire their callbacks on pool threads. Async I/O completions in HttpClient, FileStream, Socket and database drivers all resume on pool threads. Hosted services in ASP.NET Core run their async loops on it too. All of them share the same pool, which is why one part of an app that blocks threads can slow down a completely unrelated part.

Μόλις μάθεις να το ψάχνεις, το pool είναι παντού. Τα Parallel.For, Parallel.ForEach και το PLINQ σπάνε τη δουλειά τους σε κομμάτια και τα τρέχουν σε threads του pool. Τα System.Threading.Timer και System.Timers.Timer εκτελούν τα callbacks τους σε threads του pool. Οι ολοκληρώσεις async I/O στο HttpClient, στο FileStream, στο Socket και στους drivers βάσεων δεδομένων συνεχίζουν όλες σε threads του pool. Τα hosted services στο ASP.NET Core τρέχουν κι αυτά τα async loops τους πάνω του. Όλα μοιράζονται το ίδιο pool, και γι' αυτό ένα κομμάτι της εφαρμογής που κάνει block threads μπορεί να καθυστερήσει ένα εντελώς άσχετο κομμάτι.

Which tool for which job

Ποιο εργαλείο για ποια δουλειά

  • Waiting on I/O (database, HTTP, files, queues): async/await on the real async API. No Task.Run, no extra thread.
  • Short CPU-bound work you want off the current thread: Task.Run. The pool is perfect for it.
  • Lots of CPU-bound work over a collection: Parallel.ForEach or PLINQ, which use the pool and partition the work for you.
  • Long-running, synchronous, blocking work (a dedicated consumer loop, a legacy blocking API that has to run for the app lifetime): Task.Factory.StartNew with TaskCreationOptions.LongRunning, or an explicit new Thread.
  • Long-running async work: just call the async method, or use a BackgroundService in ASP.NET Core. No LongRunning.
  • Αναμονή σε I/O (βάση, HTTP, αρχεία, ουρές): async/await πάνω στο πραγματικό async API. Χωρίς Task.Run, χωρίς επιπλέον thread.
  • Σύντομη CPU-bound δουλειά που θέλεις να βγάλεις από το τρέχον thread: Task.Run. Το pool είναι ιδανικό γι' αυτό.
  • Πολλή CPU-bound δουλειά πάνω σε μια συλλογή: Parallel.ForEach ή PLINQ, που χρησιμοποιούν το pool και μοιράζουν τη δουλειά για σένα.
  • Μακροχρόνια, synchronous, blocking δουλειά (ένα αφιερωμένο consumer loop, ένα legacy blocking API που πρέπει να τρέχει όσο ζει η εφαρμογή): Task.Factory.StartNew με TaskCreationOptions.LongRunning, ή ένα ρητό new Thread.
  • Μακροχρόνια async δουλειά: απλώς κάλεσε την async μέθοδο, ή χρησιμοποίησε ένα BackgroundService στο ASP.NET Core. Χωρίς LongRunning.

Try it yourself

Δοκίμασέ το μόνος σου

Create a new console app and paste in the "Seeing the reuse" example. Run it once and note how many distinct threads handled the 100 items. Then change Thread.Sleep(10) to Thread.Sleep(500) and run it again. Before you hit Run, guess whether the number of distinct threads will go up, go down or stay the same, and why. Then print ThreadPool.ThreadCount at the end and compare it with the minimum you got from GetMinThreads.

Φτιάξε μια νέα console εφαρμογή και κάνε paste το παράδειγμα "Βλέποντας την επαναχρησιμοποίηση". Τρέξ' το μία φορά και σημείωσε πόσα διαφορετικά threads εξυπηρέτησαν τα 100 items. Μετά άλλαξε το Thread.Sleep(10) σε Thread.Sleep(500) και τρέξ' το ξανά. Πριν πατήσεις Run, μάντεψε αν ο αριθμός των διαφορετικών threads θα ανέβει, θα πέσει ή θα μείνει ίδιος, και γιατί. Μετά τύπωσε το ThreadPool.ThreadCount στο τέλος και σύγκρινέ το με το minimum που πήρες από το GetMinThreads.

Takeaways

Συμπεράσματα

  • Creating and destroying a thread is expensive: a kernel object, a reserved stack, runtime setup and more context switching.
  • The ThreadPool keeps a set of threads alive and reuses them for queued work, so you pay the creation cost once instead of every time.
  • The pool grows immediately up to its minimum, which defaults to the number of cores, and cautiously above it.
  • Task.Run queues your delegate to the ThreadPool through the default TaskScheduler. A Task is a promise of a result, not a thread.
  • TaskCreationOptions.LongRunning makes the default scheduler create a dedicated thread instead of borrowing one from the pool. Use it only for long, synchronous, blocking work, never with an async delegate.
  • await on real I/O gives the thread back to the pool while the OS waits. The continuation resumes on any free pool thread.
  • ASP.NET Core runs every request on pool threads. Blocking those threads with .Result, .Wait() or Thread.Sleep leads to ThreadPool starvation: high latency with low CPU.

Next in the series: Task Exercises, short interview exercises that put all of this into practice.

  • Η δημιουργία και καταστροφή ενός thread είναι ακριβή: ένα kernel object, ένα δεσμευμένο stack, προετοιμασία από το runtime και περισσότερο context switching.
  • Το ThreadPool κρατά ζωντανό ένα σύνολο threads και τα επαναχρησιμοποιεί για τη δουλειά που μπαίνει στην ουρά, οπότε πληρώνεις το κόστος δημιουργίας μία φορά αντί για κάθε φορά.
  • Το pool μεγαλώνει αμέσως μέχρι το minimum του, που από προεπιλογή είναι ο αριθμός των πυρήνων, και προσεκτικά πάνω από αυτό.
  • Το Task.Run βάζει το delegate σου στην ουρά του ThreadPool μέσω του default TaskScheduler. Ένα Task είναι υπόσχεση για ένα αποτέλεσμα, όχι thread.
  • Το TaskCreationOptions.LongRunning κάνει τον default scheduler να φτιάξει αφιερωμένο thread αντί να δανειστεί ένα από το pool. Χρησιμοποίησέ το μόνο για μακροχρόνια, synchronous, blocking δουλειά, ποτέ με async delegate.
  • Το await πάνω σε πραγματικό I/O επιστρέφει το thread στο pool όσο περιμένει το λειτουργικό. Το continuation συνεχίζει σε οποιοδήποτε ελεύθερο thread του pool.
  • Το ASP.NET Core τρέχει κάθε request σε threads του pool. Αν τα κάνεις block με .Result, .Wait() ή Thread.Sleep οδηγείσαι σε ThreadPool starvation: υψηλό latency με χαμηλή CPU.

Επόμενο στη σειρά: Ασκήσεις με Task, μικρές ασκήσεις συνεντεύξεων που τα βάζουν όλα αυτά σε πράξη.