This is the Reason to Avoid Using The Await Keyword in Loops
Вставка
- Опубліковано 24 кві 2024
- ►► Master Web API development Best Practices: bit.ly/3TnqoFQ
►► Build great web apps in Blazor WebAssembly: bit.ly/437g87T
►► Support us on Patreon and get the source code: / codemaze
In this video, I will show you why using await in a loop can produce some unwanted results and how we can avoid the issue with using await in a loop.
It is essential to carefully consider when to use the await keyword in a loop to prevent inefficiency and performance issues in software development. And that’s the main reason for me to create this video.
So, What Happens When the await Keyword is Added Inside a Loop?
By using await in our loop, we pause the iteration to allow the awaited method to execute before proceeding to the next iteration. Therefore, using await within our loop means we are executing everything within the loop synchronously. So, we are beating the purpose of the async and await keywords in C#.
FOLLOW US ON SOCIAL MEDIA!
►► / marinko-spasojevic
►► / codemazeblog
►► / codemazeblog
Thank you all for watching and for your support.
►► If you want to master Web API development using best practices, check out our Web API book: bit.ly/3x75ZMM
►► Also, to build great full-stack apps with Blazor, check out our course: bit.ly/3Pw3Y33
Nice tutorial thanks!
You're welcome! Thank you too for watching.
In some cases next iteration depends on previous iteration in those kind of scenarios, this will not give an expected result
I agree. That's why I said: "if you need something like this". In software design, nothing is a silver bullet and we need to consider other effects of our code. But so many times people make mistake of using the loop to execute awaitable methods that are in no way related to each other.
@@CodeMaze What about dbcontex, awaitable method calls in loop?
That really depends. But, if you create resources, the only method you need to use is the Save async method from DbContext. That one doesn't have to be in a loop because EF Core tracks changes and you can modify mulitple records and call that method only once. The main point is wether you want your loop with async methods to act sinchronoys or not. That's up to developers to make a proper decision.