采取以下方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道最好的做法是什么,上面的代码试图做什么。IAsyncEnumerable基本上从方法返回一个async。
对于我自己来说,我可以想象两种方式:
IAsyncEnumerable并立即返回结果。await foreach(var item in Bar())
{
yield return item;
}
Run Code Online (Sandbox Code Playgroud)
IAsyncEnumerable,这似乎是更好的解决方案,但仍然有点矫枉过正。return new AsyncEnumerableHolder<int>(Bar());
public struct AsyncEnumerableHolder<T>
{
public readonly IAsyncEnumerable<T> Enumerable;
public AsyncEnumerableHolder(IAsyncEnumerable<T> enumerable)
{
Enumerable …Run Code Online (Sandbox Code Playgroud)