为什么下面的代码不打印"已取消".我判断任务取消的方式有误吗?
import UIKit
class ViewController: UIViewController {
private var task: Task<Void, Never>?
override func viewDidLoad() {
let task = Task {
do {
try await test()
} catch {
if Task.isCancelled {
print("cancelled in catch block..")
}
if let cancellationError = error as? CancellationError {
print("Task canceled..")
}
}
}
self.task = task
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
task.cancel()
}
}
func test() async throws {
while true {
if Task.isCancelled {
print("cancelled..")
throw URLError(.badURL)
}
// OUTPUT:
// "cancelled.." will not be printed
// "Task canceled.." will not be printed
// "cancelled in catch block.." will not be printed
}
}
}
但是,如果我将if Task.isCancelled { print("cancelled in catch block..") }
放入CATCH块中,cancelled in catch block..
将按预期执行.