I'm working on some some Web API stuff using Entity Framework 6 and one of my controller methods is a "Get All" that expects to receive the contents of a table from my database as IQueryable<Entity>
. In my repository I'm wondering if there is any advantageous reason to do this asynchronously as I'm new to using EF with async.
Basically it boils down to
public async Task<IQueryable<URL>> GetAllUrlsAsync()
{
var urls = await context.Urls.ToListAsync();
return urls.AsQueryable();
}
vs
public IQueryable<URL> GetAllUrls()
{
return context.Urls.AsQueryable();
}
Will the async version actually yield performance benefits here or am I incurring unnecessary overhead by projecting to a List first (using async mind you) and THEN going to IQueryable?
This question is related to
c#
entity-framework
async-await
Long story short,
IQueryable
is designed to postpone RUN process and firstly build the expression in conjunction with other IQueryable
expressions, and then interprets and runs the expression as a whole.
But ToList()
method (or a few sort of methods like that), are ment to run the expression instantly "as is".
Your first method (GetAllUrlsAsync
), will run imediately, because it is IQueryable
followed by ToListAsync()
method. hence it runs instantly (asynchronous), and returns a bunch of IEnumerable
s.
Meanwhile your second method (GetAllUrls
), won't get run. Instead, it returns an expression and CALLER of this method is responsible to run the expression.
There is a massive difference in the example you have posted, the first version:
var urls = await context.Urls.ToListAsync();
This is bad, it basically does select * from table
, returns all results into memory and then applies the where
against that in memory collection rather than doing select * from table where...
against the database.
The second method will not actually hit the database until a query is applied to the IQueryable
(probably via a linq .Where().Select()
style operation which will only return the db values which match the query.
If your examples were comparable, the async
version will usually be slightly slower per request as there is more overhead in the state machine which the compiler generates to allow the async
functionality.
However the major difference (and benefit) is that the async
version allows more concurrent requests as it doesn't block the processing thread whilst it is waiting for IO to complete (db query, file access, web request etc).
Source: Stackoverflow.com