问题描述
我正在使用带有 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
是一个List.代码>.如果查看扩展方法
QueryableExtensions.ToListAsync
,你会看到它返回一个Task
.您正在异步等待此方法查询数据库、创建列表并将其返回给调用者.当您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 won't return until the operation has completed. async-await makes your code feel synchronous, while execution is actually asynchronous.
这篇关于如果我在未定义为任务的 IQueryable 上使用 await + ToListAsync() 是否正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!