Last active
November 15, 2022 17:00
-
-
Save jayrhynas/5494e6e7d286e0d9e9aa4b3614c0c7a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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