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版)
异步编程基础
31
这种设置听上去有些复杂,但所有的复杂性协同得恰如其分,因而场景简单的话,代码也
就简单。在大多数情况下,代码应将异常从其调用的异步方法上开始传播。其必行之事只
await
从异步方法中返回的任务而已,而异常便会自然地传播。
在某些情况下(比如
Task.WhenAll
),一个
Task
可能有多个异常,而
await
只会再次抛出
第一个。关于处理所有异常的示例,参见
2.4
节。
参阅
2.4
节探讨等待多个任务。
2.9
节探讨
async void
方法中的异常捕获技巧。
7.2
节探讨对
async Task
方法抛出的异常进行单元测试。
2.9
 
async void
方法的异常处理
问题
当有异常从
async void
方法中传播出来时,需予以处理。
解决方案
这个问题没有很好的解决方案。如果可以,就把方法的返回对象从
void
改为
Task
。不过
在某些情况下,这样做并不可行,比如,需要对
ICommand
实现进行单元测试,此时必须返
void
。在这种情况下,可以提供
Execute
方法的
Task
返回重载:
sealed class
MyAsyncCommand : ICommand
{
async void
ICommand.Execute(
object
parameter)
{
await
Execute(parameter);
}
public async
Task Execute(
object
parameter)
{
... // 此处为异步命令的实现
}
... // 其他部分( ...
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