如果我在未定义为任务的 IQueryable 上使用 await + ToListAsync() 是否正确
Is it correct if i am using await + ToListAsync() over IQueryable which is not defined as a task
我正在使用 asp.net MVC-5 和 EF-6,我不确定使用 await + ToListAsync
是否有效。例如,我有以下存储库方法,其中 returns 一个 IQueryable :-
public IQueryable<TSet> getAllScanEmailTo()
{
return t.TSets.Where(a=>a.Name.StartsWith("ScanEmail"));
}
我这样称呼它:-
var emailsTo = await repository.getAllScanEmailTo().ToListAsync();
一开始,我以为我会得到一个错误,因为我正在使用 "await" 一个未定义为任务的方法,但上面的方法运行良好,请问有人可以就此提出建议吗?
实际上没有问题,因为你在等待 ToListAsync()
而不是 getAllScanEmailTo()
。
编辑: 要了解异步等待模式的工作原理,您可以查看此 link。这是一张有用的图片
你不是"awaiting a method"。您正在 等待 Task
,这是一个可等待的。
您呼叫 getAllScanEmailTo
那个 returns 一个 IQueryable<TSet>
然后您呼叫 ToListAsync
returns 您正在等待的 Task<List<TSet>>
。
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
实际上,您正在等待一个return是Task<T>
的方法,其中T
是List<TSet>
。如果您查看扩展方法 QueryableExtensions.ToListAsync
,您会发现它 return 是一个 Task<List<TSource>>
。您正在异步等待此方法查询数据库、创建列表并将其 return 返回给调用者。当您在这样的方法上 await
时,在操作完成之前,该方法不会 return。 async-await 使您的代码感觉是同步的,而执行实际上是异步的。
我正在使用 asp.net MVC-5 和 EF-6,我不确定使用 await + ToListAsync
是否有效。例如,我有以下存储库方法,其中 returns 一个 IQueryable :-
public IQueryable<TSet> getAllScanEmailTo()
{
return t.TSets.Where(a=>a.Name.StartsWith("ScanEmail"));
}
我这样称呼它:-
var emailsTo = await repository.getAllScanEmailTo().ToListAsync();
一开始,我以为我会得到一个错误,因为我正在使用 "await" 一个未定义为任务的方法,但上面的方法运行良好,请问有人可以就此提出建议吗?
实际上没有问题,因为你在等待 ToListAsync()
而不是 getAllScanEmailTo()
。
编辑: 要了解异步等待模式的工作原理,您可以查看此 link。这是一张有用的图片
你不是"awaiting a method"。您正在 等待 Task
,这是一个可等待的。
您呼叫 getAllScanEmailTo
那个 returns 一个 IQueryable<TSet>
然后您呼叫 ToListAsync
returns 您正在等待的 Task<List<TSet>>
。
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
实际上,您正在等待一个return是Task<T>
的方法,其中T
是List<TSet>
。如果您查看扩展方法 QueryableExtensions.ToListAsync
,您会发现它 return 是一个 Task<List<TSource>>
。您正在异步等待此方法查询数据库、创建列表并将其 return 返回给调用者。当您在这样的方法上 await
时,在操作完成之前,该方法不会 return。 async-await 使您的代码感觉是同步的,而执行实际上是异步的。