Task: a result that comes later
“What is a Task in C#?”
An object that stands for work that has not finished yet. Like an order slip: you hold it now, the result comes later.
See it
1/8A Task is an object that stands for work that will finish later.
In plain words
Some work takes time and happens outside your code: a database query, a call to another API, reading a file. A method that starts such work does not make you wait for it. It hands you a straight away. A is an object, like an order slip at a counter: it says "your result is coming". Later the Task finishes. Then it holds the result (a holds a Loan), or the error if the work failed. You get the result out with . A plain , with no angle brackets, holds no value: it only tells you the work is done.
- A represents an operation that completes in the future. completes with a value of type T; plain completes with no value.
- A Task is not a thread. For I/O work, like a database query, no thread runs while the Task waits: the operating system tells .NET when the answer arrives.
- A Task ends in one of three states: completed with a result, faulted with an exception, or canceled through a .
- I read the result with , never with
.Resultor.Wait(), because those block the calling thread until the Task finishes.
In the lending API
A repository method from the lending API, written in two steps so you can see the Task. Press Next line to walk through it.
Lending.sln · where this file sits
- src/Infrastructure/Servicing/
What they ask next
Interviewers check that you can explain every line. Tap a question to open it.
Is a Task the same as a thread?
No. A thread is a that runs code. A Task is a promise of a result. A database query's Task uses no thread while it waits. Full comparison: .
How do I wait for two Tasks at once?
Start both, then
await Task.WhenAll(a, b). It completes when both have. Both calls run at the same time, so the total time is the slower one, not the sum.Task<Score> score = bureau.GetScoreAsync(id, ct); Task<Kyc> kyc = kycClient.CheckAsync(id, ct); await Task.WhenAll(score, kyc);
Traps
- Don't say
A Task is a background thread.SayA Task is a result that comes later. For I/O, no thread runs while it waits. - Don't say
Say.Resultis fine once you have the Task..Resultblocks the thread until the Task finishes. I always it.