func chop(_ vegetable: Vegetable) async throws -> Vegetable { await try Task.checkCancellation() // automatically throws `CancellationError` // chop chop chop ... // ... guard await !Task.isCancelled() else { print("Canceled mid-way through chopping of \(vegetable)!") throw CancellationError() } // chop some more, chop chop chop ... }
func test_cancellation_withCancellationHandler(_ anything: Any) async -> PictureData { let handle = Task.runDetached { () -> PictureData in let file = SomeFile() return await try Task.withCancellationHandler( handler: { file.close() }, operation: { await test_cancellation_guard_isCancelled(file) }) } handle.cancel() }