使用 iasyncenumerable 配合 yield return 实现流式处理。调用方通过 await foreach 遍历,数据在生成端产生后立即推送给消费端,无需等待全部完成。

IAsyncEnumerable 如何定义流式数据源?
通过标记为 async 并返回 IAsyncEnumerable 的方法定义生成器。在方法体内使用 yield return 逐个产出数据项,每次 yield 都会暂停当前执行并将控制权交还给调用方。

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class DataGenerator
{
public async IAsyncEnumerable<int> GenerateNumbers(int count)
{
for (int i = 0; i <h2>调用方如何使用 <code>await foreach</code> 消费数据?</h2>
<p>在调用端使用 <code>await foreach</code> 循环遍历异步枚举数。该语法糖会自动处理 <code>IAsyncEnumerator<t></t></code> 的生命周期管理,确保在遍历结束或发生异常时正确释放资源。数据项按顺序到达,调用方可以立即对每个项进行处理。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill2795" title="C#"><img
src="https://img.php.cn/upload/skill/000/000/081/178936933912641.jpg" alt="C#" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill2795" title="C#" class="overflowclass">C#</a>
<p class="overflowclass">"避开 C# 常见错误——空陷阱、异步陷阱、LINQ 陷阱及资源泄漏。"</p>
</div>
<a rel="nofollow" href="/xiazai/skill2795" title="C#" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<p><img src="https://img.php.cn/upload/article/001/431/639/179642309873740.png?x-oss-process=image/resize,p_40" alt="C#异步迭代器怎么边产生数据边让调用方处理?"></p>
<pre class="brush:php;toolbar:false;">using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
var generator = new DataGenerator();
await foreach (var number in generator.GenerateNumbers(5))
{
Console.WriteLine($"Processed: {number}");
}
}
}
如果在生成过程中抛出异常会发生什么?
当生成器内部抛出未捕获异常时,await foreach 会将其包装为 OperationCanceledException 或直接传播(取决于具体实现和 .NET 版本行为,通常直接传播)。调用方必须使用 try-catch 块来捕获这些异常,否则程序将终止。这种机制确保了错误能即时反馈给消费者,而不是被静默忽略。










