gpt4 book ai didi

c# - IAsyncEnumerable 的传递?

转载 作者:行者123 更新时间:2023-12-03 14:00:33 24 4
gpt4 key购买 nike

我想知道是否有一种方法可以编写一个函数来“传递”一个 IAsyncEnumerable ......也就是说,该函数将调用另一个 IAsyncEnumerable 函数并产生所有结果而无需编写 foreach去做吧?

我发现自己经常写这个代码模式。下面是一个例子:

async IAsyncEnumerable<string> MyStringEnumerator();

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;
}
}

无论出于何种原因(由于分层设计)我的功能 MyFunction想打电话 MyStringEnumerator但是然后在没有干预的情况下放弃一切。我得继续写这些 foreach循环来做到这一点。如果是 IEnumerable我会返回 IEnumerable .如果是 C++,我可以写一个宏来做到这一点。

什么是最佳实践?

最佳答案

If it were an IEnumerable I would return the IEnumerable.



好吧,你可以用 IAsyncEnumerable 做同样的事情(注意 async 被删除了):
IAsyncEnumerable<string> MyFunction()
{
// ...do some code...

// Return all elements of the whole stream from the enumerator
return MyStringEnumerator();
}

然而,这里有一个重要的语义考虑。调用枚举器方法时, ...do some code...将立即执行,而不是在枚举枚举数时执行。
// (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`
...

对于同步和异步可枚举项都是如此。

如果你想要 ...do some code...要在枚举器枚举时执行,则需要使用 foreach/ yield循环获取延迟执行语义:
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;
}

如果您也希望使用同步可枚举的延迟执行语义,则必须在同步世界中使用相同的模式:
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;
}

关于c# - IAsyncEnumerable 的传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59876417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com