简体   繁体   中英

How to cancel a thread running in the background ? (iOS)

This is my function using dispatch queue , I would like to cancel it when it is running in the background. How can I do that?

 extension DispatchQueue {
    static func background(delay: Double = 0.0, background: (()->Void)? = nil, completion: (() -> Void)? = nil) {
        DispatchQueue.global(qos: .background).async {
            background?()
            if let completion = completion {
                DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
                    completion()
                })
            }
        }
    }       
 }

 DispatchQueue.background(background: {
        do {
        }
        catch let error {
            // Error handling
        }
    }, completion:{
 })

you can make use of DispatchWorkItem with DispatchGroup.

    // create a work item with the custom code
    let workItem = DispatchWorkItem {
          // Insert your code here
    }


   //Create dispatch group
    let dispatchGroup = DispatchGroup()

   // execute the workItem with dispatchGroup
    DispatchQueue.global().async(group: dispatchGroup, execute: workItem)

   //Handle code after the completion of global queue
    dispatchGroup.notify(queue: DispatchQueue.global()) {
            print("global queue execution completed")
        }

   //when the App goes to background cancel the workItem
     workItem.cancel()

You should definitely check the Apple Official Documentation concerning :

But also this WWDC 2014

Hope it will help you and build up your knowledge base about iOS and higher level API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM