正确地将Swift闭包传递给另一个线程

时间:2017-06-19 16:26:42

标签: swift multithreading

如何正确地(从多线程的角度来看)将闭包传递给另一个线程?

考虑一下情况:

class NetManager {
    ...
    var processingClosure : (Data, DispatchQueue, @escaping (Data?) -> ()) -> () = {
        respData, complQueue, complClosure in
        let resultData = // process respData according to some logic and get resultData
        complQueue.async {
            complClosure(resultData)
        }
        // PLEASE NOTE that there is no captured variables in this closure
    }
    ...
    func requestData1(..., complClosure) {
        // this is main thread context
        // make request to endpoint 1 somehow and process result in separate processing queue
        ...
        let procClosure = self.processingClosure
        // processingQueue is NOT main queue and not completion queue 
        request.processingQueue.async {
            // Question HERE:
            procClosure(data, DispatchQueue.main, complClosure)
            // is such passing of the closure safe? Can I have issues with concurrency?
        }
    }

    func requestData2(..., complClosure) {
        // the same as requestData1 but gets data from endpoint 2
        ...
        let procClosure = self.processingClosure
        request.processingQueue.async {
            procClosure(data, DispatchQueue.main, complClosure)
        }
    }
}

这似乎是一种传递闭包的安全方法,因为它不捕获任何变量。 procClosure调用会有任何并发​​问题吗?

有没有更好的方法来封装数据转换的通用功能,以便在对不同端点的类似请求中重用(我只能封装数据处理但不能请求)?

0 个答案:

没有答案