【发布时间】:2014-09-17 21:58:25
【问题描述】:
我们使用 IEnumerables 从数据库中返回大量数据集:
public IEnumerable<Data> Read(...)
{
using(var connection = new SqlConnection(...))
{
// ...
while(reader.Read())
{
// ...
yield return item;
}
}
}
现在我们想使用异步方法来做同样的事情。但是异步没有 IEnumerables,所以我们必须将数据收集到一个列表中,直到加载整个数据集:
public async Task<List<Data>> ReadAsync(...)
{
var result = new List<Data>();
using(var connection = new SqlConnection(...))
{
// ...
while(await reader.ReadAsync().ConfigureAwait(false))
{
// ...
result.Add(item);
}
}
return result;
}
这会消耗服务器上的大量资源,因为所有数据必须在列表中才能返回。 IEnumerables 处理大型数据流的最佳且易于使用的异步替代方案是什么?我想避免在处理时将所有数据存储在内存中。
【问题讨论】:
-
这会消耗服务器上的大量资源... 那么在这种情况下,服务器执行环境是什么? (例如 ASP.NET、WCF 服务等)什么是客户端执行环境? (网络浏览器、富客户端 .NET 应用等)
-
Reactive Extensions 包括 Async Enumerable's,你应该会发现它很有帮助。
-
@ChristopherHarris,你的意思是来自 Ineteractive Extensions (Ix) 的
IAsyncEnumerable吗?可用的信息很少,例如these slides 和this blog。除了 Ix Experimental,还有其他版本吗?
标签: c# .net task-parallel-library async-await