Difference between await and using discards

Viewed 1371

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.

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.

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.

Related