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

血红的双手。 提交于 2019-12-17 20:18:31

问题


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 ?


回答1:


At the beginning I though 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 wont return until the operation has completed. async-await makes your code feel synchronous, while execution is actually asynchronous.




回答2:


Actually there is no problem because you are awating the ToListAsync() not the getAllScanEmailTo().

EDIT: To see how async-await pattern is working you can see this link. Here is a usefull image from there




回答3:


You are not "awaiting a method". You are awaiting a Task, which is an awaitable.

You call getAllScanEmailTo that returns an IQueryable<TSet> on which you then call ToListAsync which returns the Task<List<TSet>> you are awaiting.



来源:https://stackoverflow.com/questions/32759967/is-it-correct-if-i-am-using-await-tolistasync-over-iqueryable-which-is-not-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!