Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct if i am using await + ToListAsync() over IQueryable which is not defined as a task

I am using asp.net MVC-5 with EF-6, and I am not sure if using await + ToListAsync is valid. For example, I have the following repository method which returns an IQueryable :-

public IQueryable<TSet> getAllScanEmailTo()
{
    return t.TSets.Where(a=>a.Name.StartsWith("ScanEmail"));    
}

And I am calling it as follow:-

var emailsTo = await repository.getAllScanEmailTo().ToListAsync();

In the beginning, I thought I will get an error because I am using "await" a method which is not defined as a task, but the above worked well, so can anyone advice on this, please ?

like image 739
john Gu Avatar asked Sep 24 '15 11:09

john Gu


People also ask

What is ToListAsync()?

ToListAsync(IQueryable) Creates a List<T> from an IQueryable by enumerating it asynchronously. ToListAsync(IQueryable, CancellationToken) Creates a List<T> from an IQueryable by enumerating it asynchronously.

What is the difference between ToList and ToListAsync?

2 answers. ToListAsync() is ToList asynchronous. Asynchronous methods can be executed without crashing the application's main thread. Eg in a WinForms application, do not hang the GUI on long operations.

Does await block the thread?

The await operator doesn't block the thread that evaluates the async method. When the await operator suspends the enclosing async method, the control returns to the caller of the method.

What is async await in C#?

The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.


1 Answers

At the beginning I thought I will get an error because I am using "await" a method which is not defined as a task, but the above worked well

Actually, you are awaiting a method which returns a Task<T>, where T is a List<TSet>. If you look at the extension method QueryableExtensions.ToListAsync, you'll see that it returns a Task<List<TSource>>. You are asynchronously waiting on this method to query the database, create the list and return it back to the caller. When you await on such a method, the method won't return until the operation has completed. async-await makes your code feel synchronous, while execution is actually asynchronous.

like image 73
Yuval Itzchakov Avatar answered Oct 06 '22 23:10

Yuval Itzchakov