I came across some lines of code today that, boiled down, amounts to something like this:
using (var db = new AppDbContext())
{
var foo = await db.Foos
.Where(m => m.Name == "BuzzBaz" )
.FirstAsync();
foo.Name = "Quxx";
db.SaveChanges();
}
Notice the select query is async
but the call to SaveChanges() is not. It's synchronous!
Could this potentially create any problems? Should I just refactor this to use db.SaveChangesAsync();
and all is well? Or maybe just call First()
instead of FirstAsync()
? Or perhaps it's harmless and might have some benefit to overall system performance?
I found some documentation that makes me think just removing async
altogether is probably a good bet here. https://learn.microsoft.com/en-us/ef/ef6/fundamentals/async
In most applications using async will have no noticeable benefits and even could be detrimental. Use tests, profiling and common sense to measure the impact of async in your particular scenario before committing to it.