Skip to content

Instantly share code, notes, and snippets.

@JarvisTheAvenger
Created August 9, 2021 09:52
Show Gist options
  • Save JarvisTheAvenger/17132455a11f261ed5588cfab87c359b to your computer and use it in GitHub Desktop.
Save JarvisTheAvenger/17132455a11f261ed5588cfab87c359b to your computer and use it in GitHub Desktop.
import Foundation
// DispatchWorkItem
// DispatchWorkItem API is introduced in iOS 8 to provide more control over dispatch queue
// DispatchWorkItem can be used to cancel the tasks
struct Counter {
func count() {
var countWorkItem : DispatchWorkItem?
countWorkItem = DispatchWorkItem {
for value in 1..<100 {
guard let _workItem = countWorkItem,
!_workItem.isCancelled else {
debugPrint("Work item is cancelled")
break
}
debugPrint("\(value)")
sleep(1)
}
}
countWorkItem?.notify(queue: .main, execute: {
debugPrint("done counting numbers")
})
let queue = DispatchQueue.global(qos: .utility)
queue.async(execute: countWorkItem!)
queue.asyncAfter(deadline: .now() + .seconds(4)) {
countWorkItem?.cancel()
}
}
}
let counter = Counter()
counter.count()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment