If it were an IEnumerable I would return the IEnumerable.
Well, you can just do the same thing with IAsyncEnumerable
(note that the async
is removed):
IAsyncEnumerable<string> MyFunction()
{
// ...do some code...
// Return all elements of the whole stream from the enumerator
return MyStringEnumerator();
}
However, there's an important semantic consideration here. When calling an enumerator method, the ...do some code...
will be executed immediately, and not when the enumerator is enumerated.
// (calling code)
var enumerator = MyFunction(); // `...do some code...` is executed here
...
await foreach (var s in enumerator) // it's not executed here when getting the first `s`
...
This is true for both synchronous and asynchronous enumerables.
If you want ...do some code...
to be executed when the enumerator is enumerated, then you'll need to use the foreach
/yield
loop to get the deferred execution semantics:
async IAsyncEnumerable<string> MyFunction()
{
// ...do some code...
// Return all elements of the whole stream from the enumerator
await foreach(var s in MyStringEnumerator())
yield return s;
}
And you would have to use the same pattern in the synchronous world if you wanted deferred execution semantics with a synchronous enumerable, too:
IEnumerable<string> ImmediateExecution()
{
// ...do some code...
// Return all elements of the whole stream from the enumerator
return MyStringEnumerator();
}
IEnumerable<string> DeferredExecution()
{
// ...do some code...
// Return all elements of the whole stream from the enumerator
foreach(var s in MyStringEnumerator())
yield return s;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…