Hello everyone, I've worked with await/async recently but I got stuck in there . I dont know how the threads will run in system with keyword async/await?
I declare async and don't use await in the function body (it shows a warning) so is it asynchronous when calling that function?
I have 3 async functions A, B, C that I call sequentially
A
B
C
does it run asynchronously without await or need ?
await A
await B
await CI read some Microsoft document it said "when we meet the keyword 'await', the remaining code will be non-blocking and if i think code with await will cotinue running without response's waiting, is that right?"
ex:
async A(){
await something - take 5 seconds;
call api();
}
With the above code, is it Async programming ?
Thanks all guys!!!
Top comments (3)
Asynchronous programming is not something that can be explained in comments. You should get out and read as many articles as possible. Be forewarned, though, that many tutorials out there have the mindset that asynchronous programming is about multi threading. It is NOT. Multi threading is just one form of asynchronous programming.
Imagine you are cooking mashed potatoes. Let's define the process in 5 tasks:
You will do this alone. You are the thread.
You could go through the list of tasks and do this list sequentially, one task after the other. You noticed, however, that you were doing nothing while the potatoes were being cooked. You could have grated the cheese while the potatoes were cooking. So you repeat the process, this time not waiting for the potatoes to cook. Clearly this is an improvement. Now you (the thread) are able to finish faster. You have made better use of the CPU time.
In code:
So the lesson here is twofold:
await
keyword synchronizes. Only use it when you need to synchronize.Thank you very much, that's mean , I only call the async function (it will be async) and assign it to variable
var cookTask = CookPotatoes();
Not sure I follow. Are you asking a question? I'll try to guess.
With an asynchronous function, you have 2 choices: Await it, or not await it.
If you await it, the executing thread will immediately mark as "do for later" all of the code below the
await
and will go look for work to do to its task queue.If you don't await it, the asynchronous task is started, but the executing thread that started it does not wait for it to finish, and continues processing the code. This is the case I explained. Cooking is started but not awaited. The thread continued to grate the cheese while the kitchen cooktop cooked the potatoes.
Either choice is valid as long as it gets you the desired result, ideally in the fastest possible time.