Skip to content

Instantly share code, notes, and snippets.

@jayrhynas
Last active November 15, 2022 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jayrhynas/5494e6e7d286e0d9e9aa4b3614c0c7a8 to your computer and use it in GitHub Desktop.
Save jayrhynas/5494e6e7d286e0d9e9aa4b3614c0c7a8 to your computer and use it in GitHub Desktop.
import Foundation
extension DispatchWorkItem {
class func cancellable(_ work: @escaping (() -> Bool) -> Void) -> DispatchWorkItem {
class WeakBox<T: AnyObject> {
weak var value: T?
}
let box = WeakBox<DispatchWorkItem>()
let workItem = DispatchWorkItem {
work({ box.value?.isCancelled != false })
}
box.value = workItem
return workItem
}
}
import Foundation
let work = DispatchWorkItem.cancellable { isCancelled in
var i = 0
while true {
if isCancelled() {
print("cancelled")
break
}
i = i + 1
print(i)
usleep(500_000)
}
}
DispatchQueue.global().async(execute: work)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
work.cancel()
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) {
print("done")
exit(0)
}
RunLoop.main.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment