Reputation: 79
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.
Upvotes: 2
Views: 3687
Reputation: 14700
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?
await
ing 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, await
ing 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!
Upvotes: 5