C# ASP.NET Core Entity Framework Core asynchronous ToQueryable comparison

642 Views Asked by At

I am using EfRepository<TEntity> to access data and I have a DbSet<TEntity>. I'm trying to access data asynchronously and I need it is as Queryable and I'm currently using this:

public virtual async Task<IQueryable<TEntity>> AllAsync()
{
    var list = await this.DbSet.ToListAsync();
    return list.AsQueryable();
}

Is it actually faster than using the DbSet synchronously?

2

There are 2 best solutions below

1
David Browne - Microsoft On

Is it actually faster than using the DbSet synchronously?

Much, much, much slower actually. That will load all the entities into memory before returning an in-memory IQueryable.

Your additional, second-level repository should return the DbSet directly as an IQueryable<T>. It's up to the calling code to specify the query and execute it either sync or async.

Lots of people have written "generic repository" wrappers for EF. They all add complexity, and most of them do more harm than good.

3
GlennSills On

Like most things, it depends. If you are running in a console application and your goal is to completely load the list of entities into memory as fast as possible, the synchronous call will be a bit faster. If you are running queries like this in a web application then you should plan on multiples of them happening concurrently. Threads are a precious resource in a web application. Running a query synchronously will tie up a thread that could be used to handle other web requests while you query is I/O blocking. So you can maximize time to last byte by making a synchronous call, but you can maximize the overall throughput of the system (and avoid thread starvation) by using the asynchronous call.

In the end, you probably need to measure it.