Skip to content
Discussion options

You must be logged in to vote

I believe the problem is you're checking for your task cancellation incorrectly, and so the while loop runs indefinitely. Task.checkCancellation() is meant to throw an error, and you're swallowing it with try? so its unable to halt the execution.

You could instead check Task.isCancelled and break if it's true. Replace your line try? Task.checkCancellation() with the following:

if Task.isCancelled {
    break
}

You can reproduce this with the following playground:

import PlaygroundSupport

let task = Task {
	while true {
		print("task is running")

		// Try commenting out the next line and uncommenting the 3 after to see the output is only printed ~1 time
		 try? Task.checkCancellation()
…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@sillygoose
Comment options

Answer selected by sillygoose
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants