Reputation: 993
I am writing a WebAPI microservice and am wondering if there is benefit to using async
. The service makes some calls to a SQL database through Entity Framework.
Synchronous:
using(var db = new Entities())
{
var user = db.Users.FirstOrDefault();
user.IsActive = false;
db.SaveChanges();
}
Asynchronous:
using(var db = new Entities())
{
var user = await db.Users.FirstOrDefaultAsync();
user.IsActive = false;
await db.SaveChangesAsync();
}
Unlike some use cases of async
I've seen, there is no processing done between kicking off the awaitable subtasks and the suspension that comes from the await
(hence "single-threaded," though perhaps not literally).
My question is, from a resource standpoint, how is this really different from the synchronous alternative? Assuming it is asynchronous all the way through the controller, will the service scale better?
BONUS POINTS: What are the implications of doing some synchronous blocking in an otherwise asynchronous application (if a developer forgets to utilize an async method, for instance)?
Upvotes: 0
Views: 79
Reputation: 457472
I recommend you read my intro to async on ASP.NET article, especially the first half.
My question is, from a resource standpoint, how is this really different from the synchronous alternative?
The synchronous version blocks a thread in your web server until the SQL query and update are all completed. The asynchronous version does not consume a thread in your web server while the SQL query and update are in progress. Fewer threads means that your web service can more easily do other things.
Assuming it is asynchronous all the way through the controller, will the service scale better?
Your web service? Yes. Your service as a whole? It depends; specifically, it depends on how your backend scales. If it's just a single SQL server backend, then there's (probably) no point in scaling your web server because your SQL server is going to be your bottleneck. If it's a SQL cluster or Azure SQL, then (probably) using async would be beneficial to your system as a whole.
BONUS POINTS: What are the implications of doing some synchronous blocking in an otherwise asynchronous application (if a developer forgets to utilize an async method, for instance)?
Then a thread is consumed for that operation. E.g., if the asynchronous version used FirstOrDefaultAsync
with SaveChanges
(not SaveChangesAsync
), then the thread would be freed up during the query but be blocked during the save.
Upvotes: 3