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版)
166
12
再次,应该尽可能地把锁中的代码最小化。另外,需要注意阻塞调用,在理想状态下,当
锁定时,应该避免阻塞代码。
最后,避免在锁定状态下调用任意代码,包括触发事件、调用虚拟方法以及调用委托。如
果必须调用代码,那么可以在锁解除后再调用。
参阅
12.2
节探讨兼容
async
的锁,
lock
语句和
await
并不兼容。
12.3
节探讨线程间通信。
lock
语句用于保护共享数据,而不是在线程之间传递信号。
12.5
节探讨节流,这是对锁的一种泛化。锁可以当作一次一发的节流。
12.2
 异步锁
问题
假设有一些共享数据,需要从多个代码块安全地读取和写入,而这些代码块可能使用了
await
解决方案
.NET
框架的
SemaphoreSlim
类型在
.NET 4.5
中完成了更新,可以兼容
async
,下面是使用
示例:
class
MyClass
{
// 该锁保护_value
private readonly
SemaphoreSlim _mutex =
new
SemaphoreSlim(1);
private int
_value;
public async
Task DelayAndIncrementAsync()
{
await
_mutex.WaitAsync();
try
{
int
oldValue = _value;
await
Task.Delay(TimeSpan.FromSeconds(oldValue));
_value = oldValue + 1;
} ...
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