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版)
116
9
当使用类似这样的回路时,需要考虑生产者比消费者运行得快的情况。如果生产项的速度
超过消耗这些项的速度,那么可能需要节流队列。
当有单独的线程(比如线程池线程)充当生产者或消费者时,阻塞队列会非常有效。但
是,如果需要异步访问回路,它们就不那么管用了。比如让
UI
线程充当消费者,参见
9.8
节介绍的异步队列。
每当在应用程序中引入类似这样的回路时,可以考虑切换到
TPL
数据流。在
很多情况下,使用
TPL
数据流比自行建立回路及背景线程更简单。
来自
TPL
数据流的
BufferBlock<T>
可以充当阻塞队列,
TPL
数据流可以建立用于处理的
管道或网格。然而,在许多更为简单的情况下,类似
BlockingCollection<T>
的普通阻塞
队列就是恰当的选择。
AsyncEx
库的
AsyncProducerConsumerQueue<T>
也可以用作阻塞队列。
参阅
若是需要类似的回路,但要规避先进先出行为,可参考
9.7
节,这一节探讨阻塞栈和阻塞
背包。
9.8
节探讨具备异步
API
而没有阻塞
API
的队列。
9.9
节探讨节流队列。
9.12
节探讨兼具异步
API
和阻塞
API
的队列。
9.7
 阻塞栈和阻塞背包
问题
假设需要一个回路,能够在不同线程间传递信息或数据,但回路无须具有先进先出的行为。
解决方案
在默认情况下,
.NET
类型
BlockingCollection<T>
充当阻塞队列,但它也能充当任意种类
的生产者集合(或消费者集合),实际上它是对线程安全集合的包装,并且这个包装集成
IProducerConsumerCollection<T> ...
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