"What is the difference between a Thread and a Task?" is one of the most common .NET interview questions, and one of the most commonly answered wrong. Many developers think a Task is just a lighter thread. It is not. To see why, this article starts from what a thread actually is, shows how you work with threads directly in .NET and how many problems you have to solve by hand when you do, then explains why Microsoft built Task on top and how to use it correctly for the two very different kinds of work a program does: waiting for I/O and burning CPU. It is the first part of a pair. The next article, The ThreadPool in .NET, goes deeper into the pool of threads that most tasks end up running on.
"Ποια είναι η διαφορά ανάμεσα σε ένα Thread και ένα Task;" είναι από τις πιο συνηθισμένες ερωτήσεις σε συνεντεύξεις .NET, και από αυτές που απαντιούνται πιο συχνά λάθος. Πολλοί developers πιστεύουν ότι ένα Task είναι απλώς ένα πιο ελαφρύ thread. Δεν είναι. Για να φανεί γιατί, αυτό το άρθρο ξεκινά από το τι είναι στην πραγματικότητα ένα thread, δείχνει πώς δουλεύεις απευθείας με threads στο .NET και πόσα προβλήματα πρέπει να λύσεις μόνος σου όταν το κάνεις, και μετά εξηγεί γιατί η Microsoft έχτισε το Task από πάνω και πώς το χρησιμοποιείς σωστά για τα δύο πολύ διαφορετικά είδη δουλειάς που κάνει ένα πρόγραμμα: αναμονή για I/O και κάψιμο CPU. Είναι το πρώτο μέρος από δύο. Το επόμενο άρθρο, Το ThreadPool στο .NET, πηγαίνει πιο βαθιά στο pool από threads πάνω στο οποίο καταλήγουν να τρέχουν τα περισσότερα tasks.
What is a thread?
Τι είναι ένα thread;
When you start a program, the operating system creates a process for it. A process is a container: it owns a chunk of memory, open files, network sockets and other resources. But a process by itself does not execute anything. The thing that actually executes instructions is a thread.
A thread is a single sequence of instructions that the CPU runs one after the other. Every process starts with one thread, the main thread, which in a C# console app is the one that runs your Main method or your top-level statements. A process can then create more threads. All threads in the same process share the same memory, so they can all read and write the same objects. Each thread has its own:
- Stack, where its local variables and the chain of method calls live.
- Instruction pointer, which marks where in the code it currently is.
- CPU registers, the tiny pieces of state the CPU is working with right now.
A CPU core can run exactly one thread at any given instant. A machine with 8 cores can truly run 8 threads at the same time. Yet your computer right now has thousands of threads alive. The trick is the operating system's scheduler: it gives each runnable thread a short time slice, a few milliseconds, then pauses it, saves its registers and instruction pointer, and loads another thread onto the core. This is called a context switch. It happens so fast that all those threads appear to run simultaneously.
Think of a kitchen. The kitchen is the process: the fridge, the ingredients and the utensils are shared. Each cook is a thread, following their own recipe step by step, with their own notes about where they are. The stoves are the CPU cores. If there are four stoves and ten cooks, the head chef, the scheduler, keeps rotating who gets a stove. And because all the cooks share the same fridge, two of them can grab the last egg at the same moment. Keep that in mind.
Όταν ξεκινάς ένα πρόγραμμα, το λειτουργικό σύστημα φτιάχνει ένα process για αυτό. Ένα process είναι ένα δοχείο: έχει ένα κομμάτι μνήμης, ανοιχτά αρχεία, network sockets και άλλους πόρους. Αλλά ένα process από μόνο του δεν εκτελεί τίποτα. Αυτό που πραγματικά εκτελεί εντολές είναι ένα thread.
Ένα thread είναι μια μοναδική σειρά από εντολές που η CPU τρέχει τη μία μετά την άλλη. Κάθε process ξεκινά με ένα thread, το main thread, που σε μια C# console εφαρμογή είναι αυτό που τρέχει τη μέθοδο Main ή τα top-level statements σου. Μετά το process μπορεί να φτιάξει κι άλλα threads. Όλα τα threads στο ίδιο process μοιράζονται την ίδια μνήμη, οπότε όλα μπορούν να διαβάζουν και να γράφουν τα ίδια αντικείμενα. Κάθε thread έχει το δικό του:
- Stack, όπου ζουν οι τοπικές του μεταβλητές και η αλυσίδα των κλήσεων μεθόδων.
- Instruction pointer, που δείχνει σε ποιο σημείο του κώδικα βρίσκεται αυτή τη στιγμή.
- CPU registers, τα μικρά κομμάτια κατάστασης με τα οποία δουλεύει η CPU εκείνη τη στιγμή.
Ένας πυρήνας CPU μπορεί να τρέχει ακριβώς ένα thread σε κάθε στιγμή. Ένα μηχάνημα με 8 πυρήνες μπορεί πραγματικά να τρέχει 8 threads ταυτόχρονα. Κι όμως ο υπολογιστής σου αυτή τη στιγμή έχει χιλιάδες threads ζωντανά. Το κόλπο είναι ο scheduler του λειτουργικού: δίνει σε κάθε thread που θέλει να τρέξει ένα μικρό κομμάτι χρόνου, λίγα milliseconds, μετά το σταματά, σώζει τους registers και τον instruction pointer του και φορτώνει ένα άλλο thread στον πυρήνα. Αυτό λέγεται context switch. Γίνεται τόσο γρήγορα που όλα αυτά τα threads φαίνεται να τρέχουν ταυτόχρονα.
Σκέψου μια κουζίνα. Η κουζίνα είναι το process: το ψυγείο, τα υλικά και τα σκεύη είναι κοινά. Κάθε μάγειρας είναι ένα thread, που ακολουθεί τη δική του συνταγή βήμα βήμα, με τις δικές του σημειώσεις για το πού βρίσκεται. Οι εστίες είναι οι πυρήνες της CPU. Αν υπάρχουν τέσσερις εστίες και δέκα μάγειρες, ο σεφ, δηλαδή ο scheduler, εναλλάσσει συνέχεια ποιος παίρνει εστία. Και επειδή όλοι οι μάγειρες μοιράζονται το ίδιο ψυγείο, δύο από αυτούς μπορεί να αρπάξουν το τελευταίο αυγό την ίδια στιγμή. Κράτα το αυτό στο μυαλό σου.
Threads in .NET
Threads στο .NET
In .NET a thread is represented by the System.Threading.Thread class. Each managed Thread sits on top of a real operating system thread. Creating one is straightforward: you give it a method to run and call Start().
Στο .NET ένα thread αναπαρίσταται από την κλάση System.Threading.Thread. Κάθε managed Thread κάθεται πάνω σε ένα πραγματικό thread του λειτουργικού συστήματος. Η δημιουργία του είναι απλή: του δίνεις μια μέθοδο να τρέξει και καλείς Start().
Console.WriteLine($"Main runs on thread {Environment.CurrentManagedThreadId}");
var worker = new Thread(() =>
{
for (int i = 1; i <= 3; i++)
{
Console.WriteLine($" worker step {i} on thread {Environment.CurrentManagedThreadId}");
Thread.Sleep(300);
}
});
worker.Name = "Worker";
worker.IsBackground = false; // foreground: the process waits for it before exiting
worker.Start();
Console.WriteLine("Main keeps going while the worker runs");
worker.Join(); // block Main until the worker finishes
Console.WriteLine("Worker finished, Main exits");
Run it and you will see the lines from Main and from the worker interleave, on two different thread ids. A few things worth knowing about Thread:
Start()returns immediately. The new thread runs in parallel with the one that started it. There is no guarantee about which line prints first.Join()blocks the calling thread until the other thread finishes. It is the only built-in way to "wait for" a thread.- Foreground vs background. A foreground thread keeps the process alive until it finishes. A background thread (
IsBackground = true) is killed as soon as all foreground threads end. - The method returns
void. A thread runs code. It does not produce a value you can get back.
That last point is where the trouble starts.
Τρέξ' το και θα δεις τις γραμμές από το Main και από τον worker να μπλέκονται μεταξύ τους, σε δύο διαφορετικά thread ids. Μερικά πράγματα που αξίζει να ξέρεις για το Thread:
- Το
Start()επιστρέφει αμέσως. Το νέο thread τρέχει παράλληλα με αυτό που το ξεκίνησε. Δεν υπάρχει καμία εγγύηση για το ποια γραμμή θα τυπωθεί πρώτη. - Το
Join()κάνει block το thread που το καλεί μέχρι να τελειώσει το άλλο thread. Είναι ο μόνος ενσωματωμένος τρόπος να "περιμένεις" ένα thread. - Foreground έναντι background. Ένα foreground thread κρατά το process ζωντανό μέχρι να τελειώσει. Ένα background thread (
IsBackground = true) σκοτώνεται μόλις τελειώσουν όλα τα foreground threads. - Η μέθοδος επιστρέφει
void. Ένα thread τρέχει κώδικα. Δεν παράγει μια τιμή που μπορείς να πάρεις πίσω.
Αυτό το τελευταίο σημείο είναι εκεί που αρχίζουν τα προβλήματα.
The headaches of managing threads by hand
Ο πονοκέφαλος της διαχείρισης threads με το χέρι
Let's take a realistic task: compute something on a background thread, get the result back, handle the case where it fails, allow the user to cancel it, and when it is done start a second step. Here is what that looks like with raw threads:
Ας πάρουμε μια ρεαλιστική δουλειά: υπολόγισε κάτι σε ένα background thread, πάρε πίσω το αποτέλεσμα, χειρίσου την περίπτωση που αποτύχει, επέτρεψε στον χρήστη να το ακυρώσει, και όταν τελειώσει ξεκίνα ένα δεύτερο βήμα. Δες πώς μοιάζει αυτό με σκέτα threads:
long result = 0; // 1. shared variable to smuggle the result out
Exception? error = null; // 2. shared variable to smuggle the exception out
bool cancel = false; // 3. home-made cancellation flag
object gate = new();
var thread = new Thread(() =>
{
try
{
long sum = 0;
for (int i = 0; i < 1_000_000_000; i++)
{
if (cancel) return; // 4. remember to check it yourself
sum += i % 7;
}
lock (gate) result = sum; // 5. synchronize access to shared state
}
catch (Exception ex)
{
error = ex; // 6. without this, an exception kills the whole process
}
});
thread.Start();
thread.Join(); // 7. the only way to wait: block the current thread
if (error is not null) Console.WriteLine($"Failed: {error.Message}");
else Console.WriteLine($"Result: {result}");
// 8. "and then do step two": start another thread, and Join again...
Every numbered comment is a problem you had to solve yourself, and every one of them is a place to get it wrong:
- No return value. A thread cannot return a result, so you share a variable and hope you read it only after the thread has written it.
- Exceptions crash the process. An unhandled exception on a
Threaddoes not travel back to the code that started it. It terminates the entire application. Forget thetry/catchonce and your server goes down. - No built-in cancellation.
Thread.Abortwas dangerous in .NET Framework and throwsPlatformNotSupportedExceptionin .NET Core and later. You invent your own flag and check it everywhere. - Shared state needs synchronization. Two threads touching the same data without a
lockgive you race conditions, the two cooks grabbing the last egg. Locks, in turn, bring deadlocks if you take them in the wrong order. - Waiting means blocking.
Join()freezes the calling thread. If that is the UI thread, the window stops responding. - No composition. "Run these three in parallel, wait for all of them, then do X" or "whichever finishes first" means hand-written coordination with
ManualResetEvent,CountdownEventor similar primitives. - Threads are expensive. Each one costs a kernel object, about 1 MB of reserved stack and context-switching time. Creating one per small job is slow, and creating thousands brings a machine to its knees. The ThreadPool article measures this.
- Waiting for I/O wastes a whole thread. A thread that calls a database synchronously sits blocked doing nothing for the entire round trip, yet still holds all of the above.
Before 2010, .NET developers dealt with this using a zoo of patterns: ThreadPool.QueueUserWorkItem, the BeginXxx/EndXxx pairs with IAsyncResult (APM), the XxxAsync method plus XxxCompleted event (EAP), and BackgroundWorker. Each solved part of the problem, each had its own rules, and none of them composed with the others. Code that chained a few async operations quickly turned into nested callbacks that nobody wanted to touch.
Κάθε αριθμημένο σχόλιο είναι ένα πρόβλημα που χρειάστηκε να λύσεις μόνος σου, και καθένα από αυτά είναι ένα σημείο όπου μπορείς να κάνεις λάθος:
- Καμία τιμή επιστροφής. Ένα thread δεν μπορεί να επιστρέψει αποτέλεσμα, οπότε μοιράζεσαι μια μεταβλητή και ελπίζεις ότι θα τη διαβάσεις μόνο αφού το thread τη γράψει.
- Τα exceptions ρίχνουν το process. Ένα unhandled exception σε ένα
Threadδεν ταξιδεύει πίσω στον κώδικα που το ξεκίνησε. Τερματίζει ολόκληρη την εφαρμογή. Ξέχνα τοtry/catchμία φορά και ο server σου πέφτει. - Καμία ενσωματωμένη ακύρωση. Το
Thread.Abortήταν επικίνδυνο στο .NET Framework και πετάειPlatformNotSupportedExceptionστο .NET Core και μετά. Εφευρίσκεις το δικό σου flag και το ελέγχεις παντού. - Το κοινό state θέλει συγχρονισμό. Δύο threads που αγγίζουν τα ίδια δεδομένα χωρίς
lockσου δίνουν race conditions, οι δύο μάγειρες που αρπάζουν το τελευταίο αυγό. Τα locks με τη σειρά τους φέρνουν deadlocks αν τα πάρεις με λάθος σειρά. - Αναμονή σημαίνει blocking. Το
Join()παγώνει το thread που το καλεί. Αν αυτό είναι το UI thread, το παράθυρο σταματά να απαντά. - Καμία σύνθεση. Το "τρέξε αυτά τα τρία παράλληλα, περίμενε όλα, μετά κάνε το X" ή το "όποιο τελειώσει πρώτο" σημαίνει χειροποίητο συντονισμό με
ManualResetEvent,CountdownEventή παρόμοια primitives. - Τα threads είναι ακριβά. Το καθένα κοστίζει ένα kernel object, περίπου 1 MB δεσμευμένου stack και χρόνο σε context switching. Το να φτιάχνεις ένα για κάθε μικρή δουλειά είναι αργό, και το να φτιάξεις χιλιάδες γονατίζει το μηχάνημα. Το άρθρο για το ThreadPool το μετράει αυτό.
- Η αναμονή για I/O σπαταλά ένα ολόκληρο thread. Ένα thread που καλεί μια βάση synchronous κάθεται blocked χωρίς να κάνει τίποτα για όλο το round trip, κι όμως κρατά όλα τα παραπάνω.
Πριν το 2010, οι .NET developers τα αντιμετώπιζαν όλα αυτά με έναν ολόκληρο ζωολογικό κήπο από patterns: το ThreadPool.QueueUserWorkItem, τα ζευγάρια BeginXxx/EndXxx με IAsyncResult (APM), τη μέθοδο XxxAsync μαζί με το event XxxCompleted (EAP), και το BackgroundWorker. Το καθένα έλυνε ένα κομμάτι του προβλήματος, το καθένα είχε τους δικούς του κανόνες, και κανένα δεν συνδυαζόταν με τα άλλα. Κώδικας που αλυσόδενε μερικές async λειτουργίες γινόταν γρήγορα nested callbacks που κανείς δεν ήθελε να αγγίξει.
Why Microsoft created Task
Γιατί η Microsoft έφτιαξε το Task
In .NET Framework 4.0 (2010) Microsoft introduced the Task Parallel Library (TPL) and with it System.Threading.Tasks.Task. Two years later, C# 5 and .NET 4.5 added async and await, built entirely on Task. The goal was one single, composable abstraction to replace all the patterns above.
The key idea is a change of question. A Thread answers "who runs this code?". A Task answers "what is the outcome of this operation, and is it done yet?". A Task is a promise: an object that represents an operation which will finish at some point, either with a result, with an exception or by being cancelled. How the operation runs, on a pool thread, on a dedicated thread or on no thread at all, is a separate detail.
Here is the same job as before, written with Task:
Στο .NET Framework 4.0 (2010) η Microsoft παρουσίασε το Task Parallel Library (TPL) και μαζί του το System.Threading.Tasks.Task. Δύο χρόνια αργότερα, η C# 5 και το .NET 4.5 πρόσθεσαν τα async και await, χτισμένα εξ ολοκλήρου πάνω στο Task. Ο στόχος ήταν μία ενιαία abstraction που συνδυάζεται εύκολα και αντικαθιστά όλα τα παραπάνω patterns.
Η βασική ιδέα είναι μια αλλαγή ερώτησης. Ένα Thread απαντά στο "ποιος τρέχει αυτόν τον κώδικα;". Ένα Task απαντά στο "ποιο είναι το αποτέλεσμα αυτής της λειτουργίας, και έχει τελειώσει;". Ένα Task είναι μια υπόσχεση: ένα αντικείμενο που αναπαριστά μια λειτουργία που θα τελειώσει κάποια στιγμή, είτε με αποτέλεσμα, είτε με exception, είτε με ακύρωση. Το πώς τρέχει η λειτουργία, σε thread του pool, σε αφιερωμένο thread ή χωρίς καθόλου thread, είναι ξεχωριστή λεπτομέρεια.
Δες την ίδια δουλειά με πριν, γραμμένη με Task:
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
long result = await Task.Run(() => Compute(cts.Token), cts.Token);
Console.WriteLine($"Result: {result}");
await SaveAsync(result); // step two: just the next line
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancelled");
}
catch (Exception ex)
{
Console.WriteLine($"Failed: {ex.Message}"); // the exception came back to us
}
static long Compute(CancellationToken token)
{
long sum = 0;
for (int i = 0; i < 1_000_000_000; i++)
{
if (i % 1_000_000 == 0) token.ThrowIfCancellationRequested();
sum += i % 7;
}
return sum;
}
static Task SaveAsync(long value) => File.WriteAllTextAsync("result.txt", value.ToString());
Go through the same list of headaches:
- Return value:
Task<long>carries the result.awaitgives it to you. No shared variable, no lock. - Exceptions: captured inside the
Taskand rethrown at theawait, so a normaltry/catcharound the call works. Nothing crashes the process behind your back. - Cancellation: a standard
CancellationTokenthat every async API in .NET understands, fromHttpClientto EF Core. - Waiting without blocking:
awaitpauses the method, not the thread. The UI stays responsive, the server thread goes off to serve other requests. - Composition: sequential steps are just consecutive lines. Parallel steps are
Task.WhenAllandTask.WhenAny. - Cost:
Task.Runborrows a thread from the ThreadPool instead of creating one, and gives it back when done. - I/O without a thread: an I/O task, like the one from
File.WriteAllTextAsync, does not need any thread while it waits. More on this below.
Composition is where the difference is most dramatic. Downloading three pages in parallel and waiting for all of them looks like this:
Πέρνα την ίδια λίστα με τους πονοκεφάλους:
- Τιμή επιστροφής: το
Task<long>κουβαλά το αποτέλεσμα. Τοawaitσου το δίνει. Καμία κοινή μεταβλητή, κανένα lock. - Exceptions: πιάνονται μέσα στο
Taskκαι ξαναπετιούνται στοawait, οπότε ένα κανονικόtry/catchγύρω από την κλήση δουλεύει. Τίποτα δεν ρίχνει το process πίσω από την πλάτη σου. - Ακύρωση: ένα standard
CancellationTokenπου καταλαβαίνει κάθε async API στο .NET, από τοHttpClientμέχρι το EF Core. - Αναμονή χωρίς blocking: το
awaitσταματά τη μέθοδο, όχι το thread. Το UI μένει responsive, το thread του server πηγαίνει να εξυπηρετήσει άλλα requests. - Σύνθεση: τα διαδοχικά βήματα είναι απλώς διαδοχικές γραμμές. Τα παράλληλα βήματα είναι
Task.WhenAllκαιTask.WhenAny. - Κόστος: το
Task.Runδανείζεται ένα thread από το ThreadPool αντί να φτιάξει καινούριο, και το επιστρέφει όταν τελειώσει. - I/O χωρίς thread: ένα I/O task, όπως αυτό από το
File.WriteAllTextAsync, δεν χρειάζεται κανένα thread όσο περιμένει. Περισσότερα παρακάτω.
Η σύνθεση είναι εκεί που η διαφορά είναι πιο εντυπωσιακή. Το να κατεβάσεις τρεις σελίδες παράλληλα και να περιμένεις όλες μοιάζει έτσι:
using var http = new HttpClient();
Task<string> a = http.GetStringAsync("https://example.com");
Task<string> b = http.GetStringAsync("https://example.org");
Task<string> c = http.GetStringAsync("https://example.net");
string[] pages = await Task.WhenAll(a, b, c);
Console.WriteLine($"Total characters: {pages.Sum(p => p.Length)}");
Three requests in flight at once, one line to wait for all of them, exceptions from any of them surface at the await, and not a single thread is blocked while the network works. Doing the same with raw threads would take three threads, three shared variables, three try/catch blocks and three Join calls, and those three threads would spend almost their entire lives blocked.
Τρία requests σε εξέλιξη ταυτόχρονα, μία γραμμή για να τα περιμένεις όλα, τα exceptions από οποιοδήποτε εμφανίζονται στο await, και ούτε ένα thread δεν είναι blocked όσο δουλεύει το δίκτυο. Το ίδιο με σκέτα threads θα χρειαζόταν τρία threads, τρεις κοινές μεταβλητές, τρία try/catch και τρεις κλήσεις Join, και αυτά τα τρία threads θα περνούσαν σχεδόν όλη τους τη ζωή blocked.
A Task is not a thread
Ένα Task δεν είναι thread
This is the sentence to remember for interviews. A Task is an object that represents work and its eventual outcome. Sometimes a thread is running that work, sometimes no thread is involved at all. There are two very different kinds of tasks:
- Tasks that run code.
Task.Run(() => Compute())queues your delegate to the ThreadPool. While it runs, a pool thread is busy executing it. - Tasks that represent waiting.
http.GetStringAsync(url)starts a network request and hands it to the operating system. The returnedTaskjust sits there until the OS says the response has arrived. While the request is in flight, no thread is executing anything for it.
That is why you can have ten thousand pending HTTP requests in a process with only a couple of dozen threads. Each pending request is a small Task object on the heap, not a 1 MB stack. This difference maps directly to the two kinds of work your code does.
Αυτή είναι η πρόταση που πρέπει να θυμάσαι για τις συνεντεύξεις. Ένα Task είναι ένα αντικείμενο που αναπαριστά δουλειά και το τελικό της αποτέλεσμα. Μερικές φορές ένα thread τρέχει αυτή τη δουλειά, μερικές φορές δεν εμπλέκεται κανένα thread. Υπάρχουν δύο πολύ διαφορετικά είδη tasks:
- Tasks που τρέχουν κώδικα. Το
Task.Run(() => Compute())βάζει το delegate σου στην ουρά του ThreadPool. Όσο τρέχει, ένα thread του pool είναι απασχολημένο εκτελώντας το. - Tasks που αναπαριστούν αναμονή. Το
http.GetStringAsync(url)ξεκινά ένα network request και το παραδίδει στο λειτουργικό σύστημα. ΤοTaskπου επιστρέφει απλώς κάθεται εκεί μέχρι το λειτουργικό να πει ότι ήρθε η απάντηση. Όσο το request βρίσκεται σε εξέλιξη, κανένα thread δεν εκτελεί τίποτα για αυτό.
Γι' αυτό μπορείς να έχεις δέκα χιλιάδες εκκρεμή HTTP requests σε ένα process με μόνο μερικές δεκάδες threads. Κάθε εκκρεμές request είναι ένα μικρό αντικείμενο Task στο heap, όχι ένα stack 1 MB. Αυτή η διαφορά αντιστοιχεί ακριβώς στα δύο είδη δουλειάς που κάνει ο κώδικάς σου.
I/O-bound vs CPU-bound work
I/O-bound έναντι CPU-bound δουλειάς
Before you write any async code, ask one question: is my code waiting for something, or is it calculating something?
- I/O-bound work spends most of its time waiting for something outside the CPU: a database query, an HTTP call, reading or writing a file, a message queue. A faster CPU would not make it noticeably faster.
- CPU-bound work spends its time calculating: resizing images, hashing passwords, parsing a huge file already in memory, running a complex algorithm. A faster CPU, or more cores, makes it faster.
The two need different tools, and mixing them up is the most common async mistake.
Πριν γράψεις οποιονδήποτε async κώδικα, κάνε μία ερώτηση: ο κώδικάς μου περιμένει κάτι ή υπολογίζει κάτι;
- Η I/O-bound δουλειά περνά τον περισσότερο χρόνο της περιμένοντας κάτι έξω από την CPU: ένα query στη βάση, μια HTTP κλήση, ανάγνωση ή εγγραφή αρχείου, μια ουρά μηνυμάτων. Μια πιο γρήγορη CPU δεν θα την έκανε αισθητά πιο γρήγορη.
- Η CPU-bound δουλειά περνά τον χρόνο της υπολογίζοντας: αλλαγή μεγέθους εικόνων, hashing κωδικών, parsing ενός τεράστιου αρχείου που είναι ήδη στη μνήμη, εκτέλεση ενός σύνθετου αλγορίθμου. Μια πιο γρήγορη CPU, ή περισσότεροι πυρήνες, την κάνει πιο γρήγορη.
Τα δύο χρειάζονται διαφορετικά εργαλεία, και το να τα μπερδέψεις είναι το πιο συνηθισμένο λάθος στο async.
Task for I/O-bound work: async and await, no Task.Run
Task για I/O-bound δουλειά: async και await, χωρίς Task.Run
For I/O, use the real async API that the library gives you and await it. Do not wrap anything in Task.Run. The library already returns a Task that completes when the OS finishes the I/O.
Για I/O, χρησιμοποίησε το πραγματικό async API που σου δίνει η βιβλιοθήκη και κάνε του await. Μην τυλίξεις τίποτα σε Task.Run. Η βιβλιοθήκη ήδη επιστρέφει ένα Task που ολοκληρώνεται όταν το λειτουργικό τελειώσει το I/O.
public class OrderService(AppDbContext db, HttpClient http)
{
public async Task<OrderSummary> GetSummaryAsync(int orderId, CancellationToken ct)
{
// Database: EF Core sends the query and awaits the response
Order order = await db.Orders
.Include(o => o.Lines)
.FirstAsync(o => o.Id == orderId, ct);
// HTTP: call another service
var shipping = await http.GetFromJsonAsync<ShippingInfo>(
$"shipping/{orderId}", ct);
// File: append an audit line
await File.AppendAllTextAsync("audit.log",
$"{DateTime.UtcNow:O} viewed order {orderId}{Environment.NewLine}", ct);
return new OrderSummary(order.Id, order.Lines.Sum(l => l.Total), shipping!.Eta);
}
}
Each await here releases the current thread while the database, the remote service or the disk does its work. In ASP.NET Core that means the request thread goes back to the ThreadPool to handle other requests in the meantime. That is how a single server handles thousands of concurrent requests.
Two independent I/O operations can also run at the same time. Start both, then await both:
Κάθε await εδώ απελευθερώνει το τρέχον thread όσο η βάση, το απομακρυσμένο service ή ο δίσκος κάνουν τη δουλειά τους. Στο ASP.NET Core αυτό σημαίνει ότι το thread του request γυρίζει στο ThreadPool για να εξυπηρετήσει άλλα requests στο μεταξύ. Έτσι ένας μόνο server εξυπηρετεί χιλιάδες ταυτόχρονα requests.
Δύο ανεξάρτητες λειτουργίες I/O μπορούν επίσης να τρέξουν ταυτόχρονα. Ξεκίνα και τις δύο, μετά κάνε await και στις δύο:
// Sequential: ~ time(order) + time(shipping)
var order = await GetOrderAsync(id, ct);
var shipping = await GetShippingAsync(id, ct);
// Concurrent: ~ max(time(order), time(shipping))
Task<Order> orderTask = GetOrderAsync(id, ct);
Task<ShippingInfo> shippingTask = GetShippingAsync(id, ct);
await Task.WhenAll(orderTask, shippingTask);
var order2 = orderTask.Result; // safe: already completed
var shipping2 = shippingTask.Result;
One caution: an EF Core DbContext does not support two operations at the same time, so run concurrent queries on separate contexts. The rule is about the library, not about Task.
The most common I/O mistakes:
- Blocking on async:
.Result,.Wait()or.GetAwaiter().GetResult()on an incomplete task. You keep the thread blocked for the whole wait, which is exactly what async was meant to avoid, and in UI apps or classic ASP.NET it can deadlock. - Fake async:
await Task.Run(() => db.Orders.First(...)). The calling thread is released, but a pool thread is now blocked inside the synchronous call instead. Nothing was gained. - Using the synchronous API when an async one exists:
File.ReadAllTextinstead ofFile.ReadAllTextAsync,ToList()instead ofToListAsync()in EF Core.
Μια προσοχή: ένα DbContext του EF Core δεν υποστηρίζει δύο λειτουργίες ταυτόχρονα, οπότε τρέξε τα ταυτόχρονα queries σε ξεχωριστά contexts. Ο κανόνας αφορά τη βιβλιοθήκη, όχι το Task.
Τα πιο συνηθισμένα λάθη με I/O:
- Blocking σε async:
.Result,.Wait()ή.GetAwaiter().GetResult()σε task που δεν έχει ολοκληρωθεί. Κρατάς το thread blocked για όλη την αναμονή, ακριβώς αυτό που το async ήθελε να αποφύγει, και σε UI εφαρμογές ή στο κλασικό ASP.NET μπορεί να κάνει deadlock. - Ψεύτικο async:
await Task.Run(() => db.Orders.First(...)). Το thread που καλεί απελευθερώνεται, αλλά τώρα ένα thread του pool είναι blocked μέσα στη synchronous κλήση. Δεν κέρδισες τίποτα. - Χρήση του synchronous API όταν υπάρχει async:
File.ReadAllTextαντί γιαFile.ReadAllTextAsync,ToList()αντί γιαToListAsync()στο EF Core.
Task for CPU-bound work: Task.Run and Parallel
Task για CPU-bound δουλειά: Task.Run και Parallel
CPU-bound work has nothing to wait for. Marking a method async does not make a calculation faster or move it to another thread. If you write an async method that loops over a billion numbers, the caller is blocked for the whole loop, exactly like a normal method. To get CPU work off the current thread you need a thread to run it on, and that is what Task.Run gives you.
Η CPU-bound δουλειά δεν έχει τίποτα να περιμένει. Το να βάλεις async σε μια μέθοδο δεν κάνει έναν υπολογισμό πιο γρήγορο ούτε τον μεταφέρει σε άλλο thread. Αν γράψεις μια async μέθοδο που κάνει loop σε ένα δισεκατομμύριο αριθμούς, αυτός που την καλεί μένει blocked για όλο το loop, ακριβώς όπως με μια κανονική μέθοδο. Για να βγάλεις CPU δουλειά από το τρέχον thread χρειάζεσαι ένα thread να την τρέξει, και αυτό σου δίνει το Task.Run.
// WPF / WinForms button click: keep the UI responsive during heavy work
private async void OnGenerateReportClick(object sender, RoutedEventArgs e)
{
StatusText.Text = "Working...";
// The calculation runs on a pool thread, the UI thread stays free
Report report = await Task.Run(() => BuildReport(_rawData));
// Back on the UI thread, safe to touch controls
StatusText.Text = $"Done: {report.Rows.Count} rows";
}
When you have a lot of independent CPU work, for example a folder full of images to resize, you want to use all cores. Parallel.ForEach partitions the work across pool threads for you:
Όταν έχεις πολλή ανεξάρτητη CPU δουλειά, για παράδειγμα έναν φάκελο γεμάτο εικόνες για αλλαγή μεγέθους, θέλεις να χρησιμοποιήσεις όλους τους πυρήνες. Το Parallel.ForEach μοιράζει τη δουλειά σε threads του pool για σένα:
string[] files = Directory.GetFiles("photos", "*.jpg");
Parallel.ForEach(
files,
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
file => ResizeImage(file, width: 800));
// Need it awaited from UI code? Wrap the whole thing once:
await Task.Run(() => Parallel.ForEach(files, file => ResizeImage(file, 800)));
Rules for CPU-bound work:
- Use
Task.Runat the call site, where you decide to offload, not inside a library method that pretends to be async. A method calledBuildReportAsyncthat just wrapsTask.Runhides the cost from the caller. - In ASP.NET Core, usually don't offload. The request is already on a pool thread and there is no UI thread to protect.
Task.Runonly adds a thread hop. Just do the calculation, or for really heavy jobs push them to a background worker. - More threads than cores does not help. CPU work is limited by the number of cores. Starting 100
Task.Runs on an 8-core machine still runs at most 8 at a time.
Κανόνες για CPU-bound δουλειά:
- Χρησιμοποίησε το
Task.Runστο σημείο της κλήσης, εκεί που αποφασίζεις να βγάλεις τη δουλειά έξω, όχι μέσα σε μια μέθοδο βιβλιοθήκης που προσποιείται ότι είναι async. Μια μέθοδος με όνομαBuildReportAsyncπου απλώς τυλίγει έναTask.Runκρύβει το κόστος από αυτόν που την καλεί. - Στο ASP.NET Core, συνήθως μην κάνεις offload. Το request είναι ήδη σε thread του pool και δεν υπάρχει UI thread να προστατέψεις. Το
Task.Runαπλώς προσθέτει μια μετάβαση ανάμεσα σε threads. Απλώς κάνε τον υπολογισμό, ή για πραγματικά βαριές δουλειές στείλ' τες σε έναν background worker. - Περισσότερα threads από πυρήνες δεν βοηθούν. Η CPU δουλειά περιορίζεται από τον αριθμό των πυρήνων. Αν ξεκινήσεις 100
Task.Runσε μηχάνημα 8 πυρήνων, πάλι τρέχουν το πολύ 8 κάθε φορά.
Mixing both in one flow
Συνδυάζοντας και τα δύο σε μία ροή
Real code often does both: download some data (I/O), crunch it (CPU), save the result (I/O). Use the right tool for each step:
Ο πραγματικός κώδικας συχνά κάνει και τα δύο: κατεβάζει κάποια δεδομένα (I/O), τα επεξεργάζεται (CPU), αποθηκεύει το αποτέλεσμα (I/O). Χρησιμοποίησε το σωστό εργαλείο για κάθε βήμα:
public async Task ProcessDailySalesAsync(CancellationToken ct)
{
// I/O: no thread held while waiting
string csv = await _http.GetStringAsync("reports/sales-today.csv", ct);
// CPU: heavy parsing and aggregation, offloaded so the caller stays free
SalesSummary summary = await Task.Run(() => ParseAndAggregate(csv), ct);
// I/O again
await File.WriteAllTextAsync("summary.json",
JsonSerializer.Serialize(summary), ct);
}
Inside a desktop app this keeps the UI responsive through the whole flow. Inside ASP.NET Core you would usually drop the Task.Run and call ParseAndAggregate directly, for the reasons above, and keep both I/O steps async.
Μέσα σε μια desktop εφαρμογή αυτό κρατά το UI responsive σε όλη τη ροή. Μέσα στο ASP.NET Core συνήθως θα έβγαζες το Task.Run και θα καλούσες απευθείας το ParseAndAggregate, για τους λόγους που είδαμε, και θα κρατούσες και τα δύο βήματα I/O async.
When is a raw Thread still the right choice?
Πότε είναι ακόμα σωστή επιλογή ένα σκέτο Thread;
Rarely, but it happens. Use new Thread when you need control that Task deliberately hides: a thread that must run for the entire lifetime of the app doing blocking work, a specific thread priority, a single-threaded apartment (STA) for COM interop or a custom stack size. For long-running blocking work you can also stay in the Task world with TaskCreationOptions.LongRunning, which the ThreadPool article covers in detail. For everything else, start with Task.
Σπάνια, αλλά συμβαίνει. Χρησιμοποίησε new Thread όταν χρειάζεσαι έλεγχο που το Task σκόπιμα κρύβει: ένα thread που πρέπει να τρέχει για όλη τη ζωή της εφαρμογής κάνοντας blocking δουλειά, συγκεκριμένο thread priority, ένα single-threaded apartment (STA) για COM interop ή custom μέγεθος stack. Για μακροχρόνια blocking δουλειά μπορείς επίσης να μείνεις στον κόσμο των Task με το TaskCreationOptions.LongRunning, που το καλύπτει αναλυτικά το άρθρο για το ThreadPool. Για όλα τα υπόλοιπα, ξεκίνα με Task.
Try it yourself
Δοκίμασέ το μόνος σου
In a new console app, write a method that throws an exception and run it twice: once inside new Thread(...).Start() and once inside await Task.Run(...) with a try/catch around the await. Before you run it, predict what happens to the process in each case. Then replace the exception with await Task.Delay(2000) inside 1000 tasks started in a loop and awaited with Task.WhenAll, print ThreadPool.ThreadCount while they wait, and explain why the number is so small.
Σε μια νέα console εφαρμογή, γράψε μια μέθοδο που πετάει exception και τρέξ' τη δύο φορές: μία μέσα σε new Thread(...).Start() και μία μέσα σε await Task.Run(...) με ένα try/catch γύρω από το await. Πριν το τρέξεις, πρόβλεψε τι θα πάθει το process σε κάθε περίπτωση. Μετά αντικατάστησε το exception με await Task.Delay(2000) μέσα σε 1000 tasks που ξεκινάς σε ένα loop και περιμένεις με Task.WhenAll, τύπωσε το ThreadPool.ThreadCount όσο περιμένουν και εξήγησε γιατί ο αριθμός είναι τόσο μικρός.
Takeaways
Συμπεράσματα
- A thread is the unit the OS schedules on a CPU core. Threads in a process share memory but each has its own stack.
System.Threading.Threadgives you a real OS thread, with no return value, no built-in cancellation, no composition, and exceptions that crash the process.- Microsoft introduced
Taskin .NET 4.0 andasync/awaitin C# 5 to replace a zoo of older patterns with one composable abstraction. - A
Taskis a promise of a result, not a thread. It carries the result, the exception and the cancellation state. - I/O-bound:
awaitthe real async API. No thread is held while waiting. NoTask.Run. - CPU-bound:
Task.Runto get work off a special thread like the UI thread,Parallel.ForEachor PLINQ to use all cores. - Never block on async code with
.Resultor.Wait(), and never wrap synchronous I/O inTask.Runand call it async.
Next in the series: The ThreadPool in .NET, where the threads that run your tasks come from and what happens when you block them.
- Ένα thread είναι η μονάδα που το λειτουργικό προγραμματίζει πάνω σε έναν πυρήνα CPU. Τα threads ενός process μοιράζονται μνήμη αλλά το καθένα έχει το δικό του stack.
- Το
System.Threading.Threadσου δίνει ένα πραγματικό thread του λειτουργικού, χωρίς τιμή επιστροφής, χωρίς ενσωματωμένη ακύρωση, χωρίς σύνθεση, και με exceptions που ρίχνουν το process. - Η Microsoft έφερε το
Taskστο .NET 4.0 και ταasync/awaitστη C# 5 για να αντικαταστήσει έναν ζωολογικό κήπο από παλιότερα patterns με μία abstraction που συνδυάζεται εύκολα. - Ένα
Taskείναι υπόσχεση για ένα αποτέλεσμα, όχι thread. Κουβαλά το αποτέλεσμα, το exception και την κατάσταση ακύρωσης. - I/O-bound: κάνε
awaitστο πραγματικό async API. Κανένα thread δεν κρατιέται όσο περιμένεις. ΧωρίςTask.Run. - CPU-bound:
Task.Runγια να βγάλεις τη δουλειά από ένα ειδικό thread όπως το UI thread,Parallel.ForEachή PLINQ για να χρησιμοποιήσεις όλους τους πυρήνες. - Ποτέ μην κάνεις block σε async κώδικα με
.Resultή.Wait(), και ποτέ μην τυλίγεις synchronous I/O σεTask.Runκαι το λες async.
Επόμενο στη σειρά: Το ThreadPool στο .NET, από πού έρχονται τα threads που τρέχουν τα tasks σου και τι συμβαίνει όταν τα κάνεις block.