问题描述
我正在使用带有EF-6的asp.net MVC-5,并且不确定使用await + ToListAsync
是否有效.例如,我有以下存储库方法可返回IQueryable:-
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"));
}
我这样称呼它:-
var emailsTo = await repository.getAllScanEmailTo().ToListAsync();
一开始,我以为会出错,因为我使用的是"await"方法,该方法未定义为任务,但是上述方法效果很好,所以任何人都可以对此提出建议吗?
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 ?
推荐答案
实际上,您是正在等待一个返回Task<T>
的方法,其中T
是List<TSet>
.如果您查看扩展方法 QueryableExtensions.ToListAsync
,您会看到它返回了Task<List<TSource>>
.您正在异步等待此方法来查询数据库,创建列表并将其返回给调用方.当您在这样的方法上await
时,该方法将不会返回,直到操作完成. async-await 使您的代码感到同步,而执行实际上是异步的.
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.
这篇关于如果我在未定义为任务的IQueryable上使用await + ToListAsync()是否正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!