Created
August 9, 2021 09:52
-
-
Save JarvisTheAvenger/17132455a11f261ed5588cfab87c359b 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 | |
// 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