Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

When to await on a method with await keyword?


Asked by Dominik Herman on Nov 29, 2021 FAQ



When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the SynchronizationContext.Current which gets the synchronization context for the current thread.
Also,
The await keyword in C# programming language is used to suspend all async methods enclosed until the point where the operations presented by the asynchronous method are completed. In order or a developer to call multiple functions in an asynchronous way, async and await are highly used and recommended.
In respect to this, If the method that the async keyword modifies doesn't contain an await expression or statement, the method executes synchronously. A compiler warning alerts you to any async methods that don't contain await statements, because that situation might indicate an error. See Compiler Warning (level 1) CS4014.
One may also ask,
await only works inside async functions within regular JavaScript code, however it can be used on its own with JavaScript modules. await can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value.
Subsequently,
The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.