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版)
152
11
11.4
 异步属性
问题
假设要把一个属性变成异步式的,且该属性并不用于数据绑定。
解决方案
在转换现有代码使其使用
async
时,这是常见的问题。在这种情况下,属性的
getter
所调
用的方法是异步的。然而,“异步属性”之类的概念并不存在,无法对某个属性使用
async
关键字,而这恰恰是好事。
getter
应该返回当前值,而不应该启动后台操作:
// 这是我们想要的(并不会编译)
public int
Data
{
async get
{
await
Task.Delay(TimeSpan.FromSeconds(1));
return
13;
}
}
当发现代码需要“异步属性”时,你真正需要的其实略有不同。该方案取决于属性值到底
需要一次还是多次计算,于是有如下两种语义选择。
每当读取值时,该值都要异步计算。
值只异步计算一次,并被缓存下来,以便之后访问。
如果每当读取“异步属性”时,它都需要启动全新、异步的计算,那么它其实只是披着伪
装的方法。如果在转换同步代码至异步代码时遇到这种情况,那就应该承认原始设计其实
错了,属性自始至终都应该是方法:
// 作为异步方法
public async
Task<
int
> GetDataAsync()
{
await
Task.Delay(TimeSpan.FromSeconds(1));
return
13;
}
从属性直接返回
Task<int>
是可行的,如下所示:
// 该“异步属性”是异步方法
// 该“异步属性”返回Task ...
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