Skip to Content
C#并发编程经典实例(第2版)
book

C#并发编程经典实例(第2版)

by Stephen Cleary
November 2020
Intermediate to advanced
226 pages
5h 34m
Chinese
Posts & Telecom Press
Content preview from C#并发编程经典实例(第2版)
42
3
3.6
 消耗异步流
问题
假设需要处理异步流的结果,这个过程也叫作
异步枚举
解决方案
消耗异步操作可以通过
await
来实现,消耗枚举通常通过
foreach
来实现,消耗异步枚举
则要将这两者结合起来,也就是使用
await foreach
来实现。假设现在有一个异步枚举,
它会对
API
响应分页,我们可以消耗它并把每个元素写入控制台:
IAsyncEnumerable<
string
> GetValuesAsync(HttpClient client);
public async
Task ProcessValueAsync(HttpClient client)
{
await foreach
(
string value in
GetValuesAsync(client))
{
Console.WriteLine(
value
);
}
}
从概念上看,
GetValuesAsync
被调用后返回了
IAsyncEnumerable<T>
。然后,
foreach
从该
异步枚举创建了异步枚举器。在异步枚举器中,“获取下一个元素”这一操作可能是异步
的,除此之外,它在逻辑上与常规枚举器相似。因此,
await foreach
会等待下一个元素
的到来,或者等待异步枚举器完成。如有元素传来,
await foreach
会执行其循环代码体,
如果异步枚举器已经完成,则会退出循环。
对每个元素都执行异步处理也是常规做法:
IAsyncEnumerable<
string
> GetValuesAsync(HttpClient ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

解密金融数据

解密金融数据

Justin Pauley
PHP编程:第4版

PHP编程:第4版

Kevin Tatroe, Peter MacIntyre

Publisher Resources

ISBN: 9787115550606