Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between await and using discards

What is the difference between the below two lines.

await SkillReporterDatabase.Database.SaveAsync(someObject);

_ = SkillReporterDatabase.Database.SaveAsync(someObject);

Which one is preferred? Sometimes when I face some issue with await, I use _ = and it solves the problem. I couldn't see any resources online which explains the difference between these two.

like image 431
Ramesh Avatar asked Aug 28 '26 15:08

Ramesh


2 Answers

The difference is that the discard (_) doesn't care about what happens in SaveAsync once it becomes asynchronous, which it presumably does do; this has two important side effects:

  1. you won't know if the save failed
  2. if you perform any other operations via Database, you're probably going to be running overlapped operations on a single context/connection, which is not usually a supported scenario

So in this case, await is probably preferred. There are times when it is OK to discard a task, but that usually means when you start something in the background that has no further interaction with the current flow.

like image 164
Marc Gravell Avatar answered Aug 30 '26 04:08

Marc Gravell


Without the await, later operations will not be blocked by the SaveAsync call and will therefore run concurrently. The discard is just saving the Task (a task is conceptually a bit like a progress bar), not the result of the Task the way the awaited call is.

so SaveAsync returns a Task (like a promise in JavaScript). Calling await on that Task will block until the task completes and returns a result. Not calling await and instead just throwing away the Task is like throwing away a pointer in C++ -- your program will start the task and then forget about it -- it may still complete but the code in this method will never find out whether it does or not.

like image 32
jnnnnn Avatar answered Aug 30 '26 04:08

jnnnnn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!