gpt4 book ai didi

c# - 如果我在未定义为任务的 IQueryable 上使用 await + ToListAsync() 是否正确

转载 作者:可可西里 更新时间:2023-11-01 08:31:52 30 4
gpt4 key购买 nike

我正在使用带有 EF-6 的 asp.net MVC-5,我不确定使用 await + ToListAsync 是否有效。例如,我有以下返回 IQueryable 的存储库方法:-

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

我这样调用它:-

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

一开始,我以为我会得到一个错误,因为我正在使用“等待”一个未定义为任务的方法,但上面的方法运行良好,所以有人可以对此提出建议吗?

最佳答案

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 workedwell

实际上,您正在等待返回 Task<T> 的方法, 其中TList<TSet> .如果您查看扩展方法 QueryableExtensions.ToListAsync ,你会看到它返回一个 Task<List<TSource>> .您正在异步等待此方法查询数据库、创建列表并将其返回给调用者。当你await在这样的方法上,该方法在操作完成之前不会返回。 async-await 让您的代码看起来是同步的,而执行实际上是异步的。

关于c# - 如果我在未定义为任务的 IQueryable 上使用 await + ToListAsync() 是否正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32759967/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com