Skip to content

Instantly share code, notes, and snippets.

@yostane
Last active August 14, 2018 22:25
Show Gist options
  • Select an option

  • Save yostane/4aa2172e6210cac973cb27c3bb6f86c0 to your computer and use it in GitHub Desktop.

Select an option

Save yostane/4aa2172e6210cac973cb27c3bb6f86c0 to your computer and use it in GitHub Desktop.
Handling calcellation of a dispatch work item is ugly
//create the dispatch work item
var dwi2:DispatchWorkItem?
dwi2 = DispatchWorkItem {
for i in 1...5 {
print("\(dwi2?.isCancelled)")
if (dwi2?.isCancelled)!{
break
}
sleep(1)
print("DispatchWorkItem 2: \(i)")
}
}
//submit the work item to the default global queue
DispatchQueue.global().async(execute: dwi2!)
//cancelling the task after 3 seconds
DispatchQueue.global().async{
sleep(3)
dwi2?.cancel()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment