Cancellation handling lets your program stop a task that is no longer needed. This saves time and resources.
Cancellation handling in Swift
Task {
do {
try Task.checkCancellation()
// Your work here
} catch {
// Handle cancellation here
}
}Task.checkCancellation() throws an error if the task was cancelled.
Use Task.isCancelled to check cancellation without throwing.
Task {
do {
for i in 1...5 {
try Task.checkCancellation()
print("Working on step \(i)")
try await Task.sleep(nanoseconds: 500_000_000) // 0.5 seconds
}
print("Task completed")
} catch {
print("Task was cancelled")
}
}Task.isCancelled to stop a loop when cancelled.let task = Task { while !Task.isCancelled { print("Running...") try await Task.sleep(nanoseconds: 1_000_000_000) // 1 second } print("Task stopped because it was cancelled") } // Later in code // task.cancel() to stop the task
This program starts a task that prints steps with delays. After 1 second, it cancels the task. The task stops early and prints a cancellation message.
import Foundation let task = Task { do { for i in 1...10 { try Task.checkCancellation() print("Step \(i)") try await Task.sleep(nanoseconds: 300_000_000) // 0.3 seconds } print("All steps done") } catch { print("Task was cancelled") } } // Cancel the task after 1 second Task { try await Task.sleep(nanoseconds: 1_000_000_000) task.cancel() } // Keep the main thread alive to see output RunLoop.main.run(until: Date().addingTimeInterval(2))
Always check for cancellation regularly in long tasks to stop quickly.
Cancellation throws a special error, so use try/catch to handle it.
Calling task.cancel() only requests cancellation; the task must check and stop itself.
Cancellation handling helps stop tasks that are no longer needed.
Use Task.checkCancellation() or Task.isCancelled to detect cancellation.
Handle cancellation with try/catch to keep your app responsive and efficient.
Practice
Solution
Step 1: Understand cancellation handling concept
Cancellation handling is used to stop tasks that are no longer needed to save resources.Step 2: Compare options with concept
Only To stop tasks that are no longer needed matches the purpose of stopping unnecessary tasks.Final Answer:
To stop tasks that are no longer needed -> Option DQuick Check:
Cancellation handling = stop unnecessary tasks [OK]
- Thinking cancellation speeds up tasks
- Confusing cancellation with restarting tasks
- Assuming cancellation creates new tasks
Solution
Step 1: Recall correct API for cancellation check
The correct property to check cancellation is Task.isCancelled.Step 2: Verify syntax correctness
if Task.isCancelled { return } uses Task.isCancelled correctly; others use invalid method or property names.Final Answer:
if Task.isCancelled { return } -> Option BQuick Check:
Use Task.isCancelled to check cancellation [OK]
- Using incorrect method names like cancelled()
- Confusing property names with similar words
- Missing capitalization or spelling errors
Task {
for i in 1...3 {
try Task.checkCancellation()
print("Running step \(i)")
if i == 2 {
Task.current.cancel()
}
}
}Solution
Step 1: Understand Task.checkCancellation() behavior
Task.checkCancellation() throws if the task is cancelled, stopping further execution.Step 2: Analyze loop and cancellation timing
Cancellation happens when i == 2, so steps 1 and 2 print, but step 3 is skipped due to cancellation.Final Answer:
Running step 1\nRunning step 2 -> Option AQuick Check:
Cancellation after step 2 stops step 3 [OK]
- Assuming all steps run despite cancellation
- Ignoring that checkCancellation throws on cancel
- Thinking cancellation happens before step 2
Task {
if Task.isCancelled {
print("Cancelled")
}
try Task.checkCancellation()
print("Running")
}Solution
Step 1: Understand difference between Task.isCancelled and checkCancellation()
Task.checkCancellation() throws if cancelled, so it already handles cancellation detection.Step 2: Analyze redundancy of Task.isCancelled check
Checking Task.isCancelled before checkCancellation() is redundant because checkCancellation() will throw if cancelled.Final Answer:
Task.isCancelled check is redundant before checkCancellation() -> Option AQuick Check:
checkCancellation() alone suffices to detect cancellation [OK]
- Thinking isCancelled must come before checkCancellation()
- Missing try keyword (actually present here)
- Assuming no error when redundancy exists
func performTask() async {
let task = Task {
do {
for i in 1...5 {
try Task.checkCancellation()
print("Processing \(i)")
try await Task.sleep(nanoseconds: 1_000_000_000)
}
} catch {
print("Task was cancelled")
}
print("Cleanup done")
}
// User taps cancel button
task.cancel()
}Solution
Step 1: Analyze cancellation handling in the task
Task.checkCancellation() throws when cancelled, caught by catch block which prints cancellation message.Step 2: Verify cleanup code execution
Cleanup code runs after catch block, ensuring resources are cleaned up even after cancellation.Final Answer:
This code correctly cancels the task and runs cleanup after cancellation -> Option CQuick Check:
Cancellation triggers catch and cleanup runs [OK]
- Assuming cleanup won't run after cancellation
- Calling cancel() inside the task incorrectly
- Believing checkCancellation() does not throw
Ready to prove it?
Pass the test and this pattern moves unknown
