Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Entity Framework when should I use FirstOrDefaultAsync or FirstOrDefault?

I am using Entity Framework in my ASP.NET Web API. In a query method, I could either choose to use the standard LINQ method FirstOrDefault() or the EF method FirstOrDefaultAsync(). When is it correct to use one or other of these?

To my knowledge using:

var users = context.Users.FirstOrDefault(user => user.id == Id);

and

var users = await context.Users.FirstOrDefaultAsync(user => user.id == Id);

will both pause the thread they are running on until the call is returned? The only advantage of the Async method is that it can be Awaited in an Async method. However if that method is also being await then it's irrelevant? Except that you trigger another thread to be created surely?

public async Task MethodOneAsync() {
  await MethodTwoAsync();
}

public async Task MethodTwoAsync() {
  await context.Users.FirstOrDefaultAsync(..);
  ...
}

Is this the same as doing:

public async void MethodOneAsync() {
  MethodTwo();
  ... await something else to 'please' the async nature, or remove async all together ...
}

public void MethodTwo() {
  context.Users.FirstOrDefault(..);
  ...
}

Thanks, just trying to clear up my own confusion.

Note: This is the example I mean

Async method chain

Sync method chain

timings and orders

These show what I mean by a chain and the timings (9 and 0) are in milliseconds. So the Async methods took longer to run (relatively).

EDIT: In the comments it has been stated that the reason to do this is it releases the thread, however if the method being called is internal to the server then surely it's releasing one thread just to start the called code another thread?

like image 884
Tristan Trainer Avatar asked Oct 24 '25 05:10

Tristan Trainer


1 Answers

Think about other people!

I joke, but that really is the point. The synchronous method will force the thread to sit idle until the results are returned.

The asynchronous method will free up the thread to do other things while waiting. In the case of ASP.NET, for example, the thread could start working on another request for someone else that just came in. That is especially important since ASP.NET has a limited number of threads.

In a desktop app, if you're on the UI thread, it will free up the thread to respond to user input. (I'm sure you've experienced apps freeze up when they go off and do something - that's annoying)

There is a really good Microsoft article about this that should help clear things up: Asynchronous programming with async and await

like image 69
Gabriel Luci Avatar answered Oct 26 '25 19:10

Gabriel Luci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!