I thought I understood how to use async, but I'm looking at some code, and I don't get it.
Stream stream = await httpClient.GetStreamAsync(path);
What is the point of using an async method if you are just going to turn around and await it immediately?
Doesn't await effectively make this code synchronous?
What am I missing?
CodePudding user response:
If your next line depends on the stream
to do something, there's no magic that can work around that. That's a serial data dependency. Cause must come before effect, and your code must wait for the stream
to be available before it can do something with it.
Asynchrony can't change that, but it doesn't even aim to.
What it does do is free up the thread to go do other things while you wait. By using await
, you're registering this "logical thread of execution" (idk the correct term in the C#/CLR world) as being dependant on the outcome of GetStreamAsync
. Your code will stop executing, but will pick right back up automatically when the result is available. In between those two events, the thread would have been free to execute other stuff, until they too reach an await
.