Alamofire和并发操作队列 [英] Alamofire and Concurrent Operation Queues
问题描述
我在并发操作队列中使用 Alamofire (AF)在我的项目中运行网络命令。有时候,AF的完成处理程序不会触发,而使我的NSOperation挂起(等待它永远不会收到的结束消息)。
I'm using Alamofire (AF) in a concurrent operation queue to run network commands in my project. Sometimes AF's completionHandler doesn't fire, leaving my NSOperation hanging (waiting for a finish message that it will never receive).
例如。我将看到响应日志,但下面的AF的dispatch_async没有相应的看到我日志:
Eg. I'll see the "response" log, but no corresponding "see me" log from AF's dispatch_async below:
public func response(priority: Int = DISPATCH_QUEUE_PRIORITY_DEFAULT, queue: dispatch_queue_t? = nil, serializer: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?), completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
NSLog("markse-response")
dispatch_async(self.delegate.queue, {
NSLog("markse-see me")
dispatch_async(dispatch_get_global_queue(priority, 0), {
if var error = self.delegate.error {
dispatch_async(queue ?? dispatch_get_main_queue(), {
completionHandler(self.request, self.response, nil, error)
})
} else {
let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data, nil)
dispatch_async(queue ?? dispatch_get_main_queue(), {
completionHandler(self.request, self.response, responseObject, serializationError)
})
}
})
})
return self
}
这是我的NSOperation(AsynchronousCommand是NSOperation的子类):
This is my NSOperation (AsynchronousCommand is an NSOperation subclass):
import Alamofire
class SettingsListCommand: AsynchronousCommand {
override func execute() {
if cancelled { return }
let endpoint = "https://api.github.com/users/cog404/orgs"
DLogVerbose("AF request")
weak var weakSelf = self
Alamofire.request(.GET,
endpoint,
parameters:nil)
.responseJSON {(request, response, JSON, error) in
DLogVerbose("AF response")
if let strongSelf = weakSelf {
if strongSelf.cancelled {
strongSelf.finish()
return
}
DLogVerbose(JSON)
strongSelf.finish()
}
}
}
}
这仅偶尔发生,这使得调试非常困难。
This only happens 'occasionally', making this very difficult to debug.
对线程有深入了解的人知道会出什么问题吗?
Does anyone with a good understanding of threading know what could be going wrong?
任何建议非常感谢。 此处。
Any advice very much appreciated. A project to help illustrate the problem is here.
推荐答案
请求委托的分派队列是串行的,这意味着它仅一次处理一个块,以分派块(FIFO)的顺序。如果第二条日志语句未触发,则是因为前一个语句块尚未完成。
The request delegate's dispatch queue is serial, meaning that it will only process a single block at a time, in order of when the blocks were dispatched (FIFO). If the second log statement isn't firing, it's because the previous block didn't yet finish.
这篇关于Alamofire和并发操作队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!