我对取消的任务感到有些困惑。
概述:
checkCancellation
函数有 2 个子任务,一个任务运行computeA
,另一个computeB
. 它们同时运行,computeB
引发错误。
怀疑:
- 我预计子任务
computeA
会被取消,因为computeB
引发了错误,但从computeA
未被取消。 - 我的理解是错误的还是我遗漏了什么?
- 或者这是一个错误?
笔记:
- 我正在使用一个
SwiftUI
项目(因为 Swift Playgrounds 不支持async let
) macOS Big Sur 11.5.2 (20G95)
Xcode Version 13.0 beta 5 (13A5212g)
输出:
A - started
B - going to throw
A - going to return, Task.isCancelled = false
error: infinity
并发函数定义:
import Foundation
import UIKit
enum ComputationError: Error {
case infinity
}
fileprivate func computeA() async throws -> Int {
print("A - started")
await Task.sleep(2 * 100_000_000)
print("A - going to return, Task.isCancelled = \(Task.isCancelled)") //I expected Task.isCancelled to be true
return 25
}
fileprivate func computeB() async throws -> Int {
print("B - going to throw")
throw ComputationError.infinity
}
func checkCancellation() async throws {
async let a = computeA()
async let b = computeB()
let c = try await a + b
print("c = \(c)")
}
调用并发函数
struct ContentView: View {
var body: some View {
Button("check cancellation") {
Task {
do {
try await checkCancellation()
print("normal exit")
} catch {
print("error: \(error)")
}
}
}
}
}
观察:
- 当我将代码更改为
let c = try await b + a
输出:
A - started
B - going to throw
A - going to return, Task.isCancelled = true
error: infinity
怀疑:
我仍然不确定我是否理解原始代码中这种行为的原因