2

My scenary is something like this

//a lot of database dependant processing

db.SaveChangesAsync(); //asynchronouly saving database changes

//a lot of ANOTHER long term database INDEPENDANT stuff

since await db.SaveChangesAsync() waits until all changes are made to database (could take some time) and I don't want to wait, but in paralell I want to make the other log term stuff below WHILE SaveChanges is saving changes, why should I use await? If I dont use await I receive the worning in the image below. enter image description here

  • 1
    I don't think you understand what `await` is actually doing here. If you don't await it, th emethod might exit before it's actually done it's job. Also `await` doesn't mean that it waits for the method to complete before moving on to the next line. – DavidG Apr 06 '17 at 19:27
  • I think I was mixing two different concepts: paralellism and asynchrony. I was reading this thread http://stackoverflow.com/questions/4844637/what-is-the-difference-between-concurrency-parallelism-and-asynchronous-methods to figure out how I could gain some responsiveness in a windows forms application. But I still can't anderstand how I could gain some performance in an asp.net MVC application. – Vitor Luiz Rubio Apr 07 '17 at 20:35

1 Answers1

5

This warning is quite clear - you're starting an asynchronous task, but you have no mechanism for being notified when it's complete. What if you do need to know when it's done, later? Before returning from your method, or at a point where you need to be sure that the data is synchronized with the DB?

awaiting the operation is one way to ensure that, but as you say, you don't want to stop the independent processing while the data is saved. await is for asynchrony, not for parallelism.

Additionally, awaiting the Save task ensures that you catch any exceptions that are thrown by the DB. When you simply release the task, any exceptions are lost - at best, you can handle TaskScheduler.UnobservedTaskException to handle unobserved tasks that throw exceptions, but a much simpler way is to simply observe the task.

One way to observe the task is await, as you know. Another is to simply save the Task object that SaveChangesAsync returns in a variable. This will allow you to await (or Wait()) on that Task later, catch its exceptions (either by try/catching the await call or by attaching a ContinueWith to the Task) and will let the compiler rest easy knowing you're not abandoning the task to its fate:

//a lot of database dependant processing
var dbSaveTask = db.SaveChangesAsync(); //asynchronouly saving database changes
//a lot of ANOTHER long term database INDEPENDANT stuff
// now, before assuming the DB is up to date, ensure the TAsk is complete. 
await dbSaveTask;
// now do something Db-dependent!
Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63