Возьмите следующие методы:
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;
}
}
Интересно, что было бы лучше всего делать, как пытается описанный выше код. В основном, возвращая IAsyncEnumerable
из async
метода.
Для себя я могу представить два пути:
- Итерация по
IAsyncEnumerable
и немедленный возврат результата.
await foreach(var item in Bar())
{
yield return item;
}
Создание структуры, которая может временно хранить
IAsyncEnumerable
, что кажется лучшим решением, но все же является излишним.
return new AsyncEnumerableHolder<int>(Bar());
public struct AsyncEnumerableHolder<T>
{
public readonly IAsyncEnumerable<T> Enumerable;
public AsyncEnumerableHolder(IAsyncEnumerable<T> enumerable)
{
Enumerable = enumerable;
}
}
Есть ли лучший способ добиться такого поведения?