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版)
154
11
public int
Data
{
// 不合格的代码!
get
{
return
GetDataAsync().Result; }
}
虽然这里讨论的主题是
async
代码中的属性,但也不妨思考一下状态与异步代码之间存在
何种关联。在把代码主体从同步转换为异步时,这一点尤为关键。回想所有在
API
中暴露
的状态(比如通过属性),针对每个状态,反思对于正处于异步操作进程中的对象,其当
前状态是什么?这并没有标准答案,但思考所需要的语义并在文档中记录它们,这一点是
很重要的。
Stream.Position
为例,它表示流指针的当前偏移量。当使用同步
API
调用
Stream.Read
Stream.Write
时,便会完成读操作或写操作,并且在
Read
方法或
Write
方法返回之前,
Stream.Position
会更新,从而反映新位置。同步代码的语义很清楚。
现在来看看
Stream.ReadAsync
Stream.WriteAsync
,考虑下面几个问题。
Stream.Position
应该在何时更新?是在读操作或写操作完成时,还是在它们实际发生之前?如果在操作完
成之前更新,那是在
ReadAsync
WriteAsync
返回时同步更新,还是在这不久之后更新?
此例很好地展示了怎样让暴露状态的属性针对同步代码具有完全清晰的语义,而对异步代
码没有明显正确的语义。这并非世界末日,只需在把类型异步化时顾及整个
API
,并在文
档中记录选择的语义即可。
参阅
14.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