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版)
异步编程基础
33
AsyncContext
类型可以在
Nito.AsyncEx
NuGet
包中获取。
参阅
2.8
节探讨
async Task
方法的异常处理。
7.3
节探讨
async void
方法的单元测试。
2.10
 创建
ValueTask
问题
需要实现一个方法,让它返回
ValueTask<T>
解决方案
在有同步结果返回、异步操作较为罕见的场景中,可将
ValueTask<T>
用作一种返回类
型。这里也有一条准则,那就是对于自写的应用程序代码,应当使用
Task<T>
作为返回类
型,而不是使用
ValueTask<T>
。当且仅当使用
ValueTask<T>
作为返回类型能够提升性能
时,才可以考虑使用它。因此,在某些情况下,需要实现一种返回
ValueTask<T>
的方法。
IAsyncDisposable
就属于这类情况,它的
DisposeAsync
方法会返回
ValueTask
。要浏览有
关异步丢弃的更多信息,参见
11.6
节。
要实现返回
ValueTask<T>
的方法,最简单的途径就是使用
async
方法和
await
方法,如同
对待常规的
async
方法一样:
public async
ValueTask<
int
> MethodAsync()
{
await
Task.Delay(100); // 异步工作
return
13;
}
很多时候,返回
ValueTask<T>
的方法也能立刻返回一个值。在这种情况下,可以使用
ValueTask<T>
构造函数优化该场景,然后只需要在必要时发送到缓慢的异步方法中:
public ...
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