Take the following the methods:
public async IAsyncEnumerable<int> Foo()
{
await SomeAsyncMethod();
return Bar(); // Throws since you can not return values from iterators
}
public async IAsyncEnumerable<int> Bar()
{
for(int i = 0; i < 10; i++)
{
await Task.Delay(100);
yield return i;
}
}
I wonder what the best practice would be, to do, what the code above tries to. Basically returning an IAsyncEnumerable
from an async
method.
For myself I can imagine two ways:
- Iterating over the
IAsyncEnumerable
and yielding the result immediately back.
await foreach(var item in Bar())
{
yield return item;
}
- Creating a struct which can store an
IAsyncEnumerable
temporarily, which seems to be the better solution, but still kind of overkill.
return new AsyncEnumerableHolder<int>(Bar());
public struct AsyncEnumerableHolder<T>
{
public readonly IAsyncEnumerable<T> Enumerable;
public AsyncEnumerableHolder(IAsyncEnumerable<T> enumerable)
{
Enumerable = enumerable;
}
}
Is there any better way to achieve this behavior?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…