Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the benefit with using Async in an ASP.Net WebAPI method with EF?

I recently asked a question and was given two answers:

The sync version:

var phrasesCount = db.Phrases.Count();
The async version (assuming this is EF):

var phrasesCount = await db.Phrases.CountAsync();

Can someone explain to me what the difference is and why I might want to use Async?

like image 527
Alan2 Avatar asked Mar 11 '23 00:03

Alan2


1 Answers

The worker process where your app is running has a limited number of threads available to handle http requests. The goal is to keep those threads free so that they are available to handle incoming requests. The async version does not block the calling thread. This allows that thread to get back to handling those incoming http requests. In the meantime, the async method has been fired off and when it completes, execution will pick up where it left off at the await operation. If you are running your app and testing the difference between the two using your example, you will not see much of a difference between performance. The real value comes when your app has more requests incoming than there are threads available to process them.

like image 188
knobcreekman Avatar answered Mar 29 '23 23:03

knobcreekman