[英]await IAsyncEnumerable<T> where is it used?
- Starting with C# 8.0,
IAsyncEnumerable<T>
, for an async method that returns an async stream .从 C# 8.0 开始,
IAsyncEnumerable<T>
,用于返回异步 stream的异步方法。
Question .问题。 In addition to the specified example with
foreach
, is it possible to use more the await
with IAsyncEnumerable<T>
somehow, or is it designed specially for foreach
?除了指定的
foreach
示例之外,是否可以通过IAsyncEnumerable<T>
以某种方式使用更多的await
,或者它是专门为foreach
设计的? I think yes, but not sure.我认为是的,但不确定。 Perhaps there are other purposes.
也许还有其他目的。
await foreach (var number in GetNumbersAsync())
{
Console.WriteLine(number);
}
async IAsyncEnumerable<int> GetNumbersAsync()
{
for (int i = 0; i < 10; i++)
{
await Task.Delay(100);
yield return i;
}
}
As Jeremy Lakeman said in the comments, you can use it however you want.正如 Jeremy Lakeman 在评论中所说,您可以随心所欲地使用它。 There is nothing magic about it.
它没有什么神奇之处。 Simply call
.GetAsyncEnumerator()
on your IAsyncEnumerable
and then you can use that as you would a regular enumerator, but with async support.只需在您的
IAsyncEnumerable
上调用.GetAsyncEnumerator()
,然后您就可以像使用常规枚举器一样使用它,但支持异步。
Example:例子:
IAsyncEnumerator<int> e = GetNumbersAsync().GetAsyncEnumerator();
try
{
while (await e.MoveNextAsync())
Console.Write(e.Current + " ");
}
finally {
if (e != null)
await e.DisposeAsync();
}
The sample was taken from here: https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8样本取自此处: https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8
When compiled, foreach
becomes like:编译后,
foreach
变成:
IAsyncEnumerator<int> e = RangeAsync(10, 3).GetAsyncEnumerator();
try
{
while (await e.MoveNextAsync()) Console.Write(e.Current + " ");
}
finally { if (e != null) await e.DisposeAsync(); }
the github.com/dotnet/reactive project includes the System.Linq.Async library, which provides a full set of such extension methods for operating on IAsyncEnumerable.
github.com/dotnet/reactive项目包括 System.Linq.Async 库,它提供了一套完整的此类扩展方法,用于在 IAsyncEnumerable 上进行操作。 You can include this library from NuGet in your project, and have access to a wide array of helpful extension methods for operating over IAsyncEnumerable objects.
您可以在您的项目中包含来自 NuGet 的这个库,并可以访问各种有用的扩展方法来操作 IAsyncEnumerable 对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.