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版)
集合
115
9.6
 阻塞队列
问题
假设需要一个回路,能够在不同线程间传递信息或数据。比如,一个线程可以加载数据,
在加载过程中顺着回路向下推动,同时,回路接收端的其他线程负责接收并处理数据。
解决方案
.NET
类型
BlockingCollection<T>
就是为此类回路设计的。在默认情况下,
Blocking-
Collection<T>
是一种阻塞队列,具有先进先出的特点。
阻塞队列需要在多个线程间共享,而且通常定义为私有、只读的域:
private readonly
BlockingCollection<
int
> _blockingQueue =
new
BlockingCollection<
int
>();
通常,线程要么向集合添加项,要么从集合移除项,但这两种情况不会同时发生。添加项
的线程叫作
生产者线程
,移除项的线程则叫作
消费者线程
生产者线程可以通过调用
Add
来添加项,当生产者线程结束时,也就是当所有项都已经添
加时,它可以通过调用
CompleteAdding
来完成集合。这会通知集合没有其他项需要添加,
随后集合会通知其消费者没有其他可添加的项。
下面这个简单的生产者样例先添加了两项,随后将集合标记为“完成”:
_blockingQueue.Add(7);
_blockingQueue.Add(13);
_blockingQueue.CompleteAdding();
消费者线程通常循环运行,等待下一项,然后进行处理。如果把生产者代码放入单独的线
程里(比如通过
Task.Run
),便可以消耗这些项,如代码示例所示: ...
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