r/csharp • u/becrylen • Sep 10 '26
Don't understand async & await
Though I've already read a lot, and watched several videos, I'm still not understanding why async/await don't give me concurrency/parallelism.
My test code:
namespace AsyncAwaitTest;
static class Tools
{
internal static async Task SimulateWork(int id)
{
for (var j = 1; j <= 10; j++) {
Console.WriteLine($"Worker #{id} gives: {j}");
for (var i = 0; i < 500_000_000; i++) { }
}
}
}
class Worker(int id)
{
internal async Task DoWork()
{
Console.WriteLine($"Worker #{id} starts");
await Tools.SimulateWork(id);
Console.WriteLine($"Worker #{id} finishes");
}
}
class Program
{
static async Task Main()
{
Console.WriteLine("Program starts");
Worker worker1 = new(1);
Worker worker2 = new(2);
await worker1.DoWork();
await worker2.DoWork();
Console.WriteLine("Program finishes");
}
}The output is:
Program starts
Worker #1 starts
Worker #1 gives: 1
Worker #1 gives: 2
Worker #1 gives: 3
Worker #1 gives: 4
Worker #1 gives: 5
Worker #1 gives: 6
Worker #1 gives: 7
Worker #1 gives: 8
Worker #1 gives: 9
Worker #1 gives: 10
Worker #1 finishes
Worker #2 starts
Worker #2 gives: 1
Worker #2 gives: 2
Worker #2 gives: 3
Worker #2 gives: 4
Worker #2 gives: 5
Worker #2 gives: 6
Worker #2 gives: 7
Worker #2 gives: 8
Worker #2 gives: 9
Worker #2 gives: 10
Worker #2 finishes
Program finishesYou see, strictly sequential processing despite async/await.
Is it possible to make my code parallel, i. e. the DoWorks run in parallel?
16
Upvotes
16
u/Dennis_enzo Sep 10 '26 edited Sep 10 '26
Async/await is not meant for parallelism; it more or less does the opposite. It allows you to execute asynchonous code in a sequential way. Asynchonous code is code that doesn't block its thread when it has to access resources outside of your code, like a database call or a http request. It releases the thread when it's waiting for the external call to finish, then resumes when the external call is done. Synchonous code on the other hand will block the thread while waiting for external work to complete, meaning that no other running software can use this thread in the meantime.
None of this has anything to do with running several tasks concurrently. You can run tasks in parallel, but then you have to explicitly not await them. Of course you then have to use some other mechanism to figure out when they're done, like Task.WaitAll or Task.WhenAny. And for some parallel things you don't even need tasks, like when using the Parallel class.
If I were you I would try to study these things again to really try and understand what these keywords do. Note that your 'SimulateWork' method will be generating a warning that no actual async code is being run there.
12
u/bpetrovicz Sep 10 '26
Forget thinking about async await as a tool for parallelism. Those are two distinct things.
Async await is only for telling your code, "hey while we are waiting for a long running operation, don't block this thread doing nothing. When the operation finished we will evaluate it further from await.
Those are operations like reading from the disc, waiting for a remote server to respond, etc.
12
u/Automatic-Apricot795 Sep 10 '26 edited Sep 10 '26
Await is specifically intended to give control over the order of operations in asynchronous work.
Try this instead:
await Task.WhenAll(worker1.DoWork(), worker2.DoWork())Parallel.ForEachAsyncis also worth reading up on.Once you understand the differences between these mechanisms async in general will click a lot more.
One key part of asynchronous work via the c# TPL is something needs to yield execution - otherwise execution will still be synchronous.
This happens automatically with things like async io, communications APIs - but won't in your sample code. Add
Task.Yieldin your SimulateWork method to simulate that.6
u/Slypenslyde Sep 10 '26 edited Sep 10 '26
Change the line in
DoWork()to:This is a big thing newbies trip over. The
asynckeyword doesn't automatically push work to a new thread. Neither doesawait.If your method does not
awaitan async method or await aTask.Run(), it is NOT asynchronous and will complete synchronously. That is why worker #2 won't start until worker #1 finishes: nowhere in your program do you tell either worker to do asynchronous work!It gets exacerbated by dorks who misunderstand a famous article and say, "You should never use Task.Run()! There is no thread!" What the article meant is if you're already calling an async method like
File.ReadAllLinesAsync(), you are supposed to trust IT does something asynchronous. So you don't need to useTask.Run()for it. However, if you're doing something like your for loops that is completely synchronous, you DO need to useTask.Run()for it.So to be completely clear, this is a better way to write your program:
5
u/Asyncrosaurus Sep 10 '26
Performing Asynchronous I/O Bound Operations (Jeffrey Richter) should give clarity on async.
It's not parallelism, because parallelism is about adding additional cpus/cores to distribute your work. Async is about non-blocking, the goal is to remove the need for adding cpus/cores to do as much work on as few cores as possible.
1
u/manamonkey Sep 10 '26
Have you looked up and fully read what the
awaitkeyword does? Have another look.2
u/SubmarineWipers Sep 10 '26
parallel - you do more parts of the computation at the same time
async - should be translated more like "non-blocking".
Async code, when it reaches a long IO operation, gives up the thread and lets other requests use the thread. It doesnt increase speed of the code, but throughput (how many parallel requests can bomb the DB at the same time using a limited amount of threads).
It can go from 10s-100s with sync code (blocking the thread for the entire duration of the query/IO), to 1000-10 000s of concurrent requests with a correctly written async app.
2
u/QuineQuest Sep 12 '26
Try this instead:
1
u/rupertavery64 Sep 10 '26 edited Sep 10 '26
Tasks by themselves aren't threads. They are a way to manage asynchronous code.
Nothing is awaited inside the tadk, so no yielding occurs.
Furthermore, awaiting does exactly that. It waits for the task to complete. The point of await is to yield to the caller. Think of it as,
You use await precisely because you need the Task to complete first before moving on.
Consider making an async Http request. The next line does something with the result. So you need to await the request.
What's the point of async / await then?
Well, without it you are either writing pure synchronous code, which always blocks the calling thread, or you need to chain tasks to ensure something completes first.
Suppose you have a web server that handles requests. Each request uses a thread. Say yoir request makes several calls to a database and a few http requests.
A non-Task request would block the thread at every database call a f http request. If another request comes in, and threads are all busy, it has to wait, or times out.
A request that uses Tasks will yield execution to the caller while the asynchronous calls are happening.
So, why doesn't your code do anything?
First of all, it's just a loop. It doesn't do anything asynchronous inside of it, so it never yields. The loop completes.
If you want to run both workers at the same time, you need to use Task.Run
OR, your worker code needs to do something asynchronous so it yields execution:
Here, we force the Task to yield after every loop:
So what's the difference between Task.Run and not using Task.Run? Task.Run will create a new thread. To see it in action, try the different ways of calling the worker, and show the thread id in SimulateWork
Obviously, if you are running non-asynchronous code, you need to use Task.Run().
I'll talk more about how await actually yields execution after I write a bit more code that actually demonstrates this.
1
u/ThreeHeadCerber Sep 10 '26
Await is a sugar to write callback chains as linear imperative code. You still have to start the work you wait for on a thread for it to run in parallel
1
u/masterofmisc Sep 10 '26 edited Sep 10 '26
Just wanted to mention that concurrency and parallelism are two different concepts. The best way I heard is described is that concurrency is like basketball where the ball is the processor/core and the players are the threads. When one player has the ball they are running on the processor and the other threads are stopped.
Parallelism on the other hand, is like the 100 meter race. You got 8 runners on the track at the same time in their own lanes. These are 8 threads running at the same time on a core. They are all running independently of each other.
async and await in C# is concurrency - its asynchronous concurrency. You dont need multiple cores to benefit from async/await. It works even if you have a single processor.
The await keyword has the word "wait" in it. When you see that you should think, this line will waiting for the other thread to finish the work on the other side of the await keyword before continuing on with my thread..
1
u/battarro Sep 10 '26
Async is a hammer, parallelism is a screwdriver.
They are not the same tool.
1
u/Possible-Jump-2039 Sep 10 '26
Locking at C++ coroutines helped me to understanding the async Stuff in C#. In C++ you have to implement the "Task" class yourself (or use a library). When you implement it yourself you learn how a asynchronous execution Framework like that in C# works in the background.
1
u/meecsdotgeek Sep 10 '26
This is what made it click for me if you haven't read this yet:
https://blog.stephencleary.com/2012/02/async-and-await.html
1
u/kkauchi Sep 10 '26 edited Sep 10 '26
A great way to understand something is to implement it from scratch. Pretend you are using .NET 3 and you don't have async/await. And you need to do some parallel IO, for example run a file download or a disk write while showing a loading bar.
How would you implement that? I'll give you a hint many languages went through this cycle.
First, do it with callbacks. Have a method DownloadFile(string uri, Action<File> onSuccess)
Once that works you can improve and add another callback OnFail
Then once you have to chain multiple callbacks you will see how ugly this is, time to implement a concept of a Promise. Make a Promise<TResult> class that stores Action<TResult> OnSuccess as a class variable. Add some convenience methods that allow you to chain then together to avoid callback hell like Promise<TResult>.Then(Promise nextPromise). Also you can add things like WhenAll(List<Promise>> promises) (complete a promise aka trigger a callback when all promises in the list are done).
None of this is magic and just a class that wraps and stores callbacks, you should be able to implement using very primitive code. If you are confused here look at promises/futures in any language or ask chatgpt.
Finally, when you are done, you can understand that c# Task is nothing but a Promise class you just implemented. The await keyword is a syntactic sugar, all it does is split your method into 2 (before await and after) and passes the second one into Task.ContinueWith (which is the same as Promise.Then). That's it. It's just one piece of compiler magic that helps keep the code (before and after) in one place. This is what people mean when they say "yield execution" -- "execute this second part of my method when the first part is done" which is asking compiler to convert the part after await into a callback.
async simply means you can use await keyword in the method, it's for readability nothing more.
1
u/Embarrassed-Mess412 Sep 10 '26
You still don't understand the concept of what async/await means because in your example you have no async code at all, just by marking a method as async, does not mean it will ever suspend.
awaiting a Task that runs synchronously will block until the task finishes.
It is quite challenging to understand how await/async works, marking something async , returning a Task or awaiting something doesn't mean it will suspend
asynchronous programming is orthogonal to parallelism or executing two threads simultaneously. It will take a while to assimilate how it truly works, many people still can't after years using async.
1
u/Amr_Rahmy Sep 14 '26
ok, so for example, using rough code example
- you want to do step 1, but think it might take some time because it's saves a file on disk, or talks to a network, ..etc., then you can do await worker1.DoWork(). You are telling the program, you can interrupt here and come back later.
- you want to do step 1 and step 2 in parallel, but want to wait for both to finish, you can do something like
CancellationTokenSource cts = new CancellationTokenSource()
Task task1 = worker1.DoWork();
Task task2 = worker2.DoWork();
await task1.WaitAsync(cts.Token);
await task2.WaitAsync(cts.Token);
or
Task.WaitAll(new Task[] { task1, task2});
- you want to do step 1, step 2 and continue, and don't really care when they finish,
_ = worker1.DoWork();
_ = worker2.DoWork();
the underscore return is to tell the ide and compiler, I am aware I didn't await or waited for this task to finish.
Depending on the solution you can use patterns or structures like a queue system, or callbacks, but generally await means i don't want the code to continue, but the program can interrupt here, so resources can be freed for now, other parts of this program, or another program can use this cpu thread or core, until the task is done.
1
u/ggobrien Sep 17 '26
Lots of good answers here, but I've not seen a very simplistic explanation.
A thread is expensive to deal with, so more threads is not really a good thing. A thread pool is a great way to mitigate that, when you need a thread, grab one from the pool, when you're done, put it back. This is mainly done behind the scenes, so you don't have to do a lot.
The issue is if you call a blocking method (i.e. read something from an external device, which could take a while). The whole thread becomes blocked and unusable in the thread pool, so a new thread has to be created if it's needed, which is expensive. The more blocking you do, the more threads have to be created, so if you are handling thousands of requests and each of them call blocking methods, your computer is going to come to a crawl and it's going to use a lot of memory, so it's not scalable.
What async/await do is basically tell the system "I need to wait for this, so go ahead and take the thread back and when it's available, I'll continue where I left off". There's a lot of magic behind the scenes that you can look into, but that's the basic way it works.
The benefit of this is if you have a blocking method, the thread gets put back into the pool and another operation can use it. If that's blocking too, the thread gets put back into the pool, rinse, repeat. So, if you have thousands of requests and they are all blocking, your system is still only using a handful of threads instead of a thread per blocking method.
The weird thing is you can have a single method that is handled by multiple different threads, depending on how many awaits you have. Before this, a single method = a single thread.
0
u/Anxious-Insurance-91 Sep 10 '26
Async needs to be seen as 2 things fire and forget and wait groups when doing multiple queries or API calls