如何取消后台运行的线程? (IOS)

时间:2018-03-13 09:16:10

标签: ios swift multithreading asynchronous background

这是我使用调度队列的功能,我想在后台运行时取消它。我怎么能这样做?

 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:{
 })

2 个答案:

答案 0 :(得分:3)

您可以将DispatchWorkItem与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()

答案 1 :(得分:0)

您一定要查看有关以下内容的Apple官方文档:

但是这个WWDC 2014

希望它能帮助您建立有关iOS和更高级别API的知识库。