我只想在 Alamofire
上一次处理一个请求 - 这意味着当第一个请求的响应到来时,它将处理第二个请求,依此类推。
如何实现?
最佳答案
基本上你可以从几种方法中选择一种:
使用
NSOperationQueue
- 使用maxConcurrentOperationCount = 1
创建队列,然后简单地将任务添加到队列中。示例:let operationQueue:NSOperationQueue = NSOperationQueue() operationQueue.name = "name.com" operationQueue.maxConcurrentOperationCount = 1 operationQueue.addOperationWithBlock { //do staff here }
如果您需要取消所有任务 -
operationQueue.cancelAllOperations()
使用
信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0) request.execute = { //do staff here dispatch_semaphore_signal(sema) } dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) //or dispatch_semaphore_wait(semaphore, dispatch_time( DISPATCH_TIME_NOW, Int64(60 * Double(NSEC_PER_SEC)))) //if u need some timeout dispatch_release(semaphore)
GCD
和DISPATCH_QUEUE_SERIAL
let serialQueue = dispatch_queue_create("name.com", DISPATCH_QUEUE_SERIAL) func test(interval: NSTimeInterval) { NSThread.sleepForTimeInterval(interval) print("\(interval)") } dispatch_async(serialQueue, { test(13) }) dispatch_async(serialQueue, { test(1) }) dispatch_async(serialQueue, { test(5) })
Mutex
- 简单示例 from here :
pthread_mutex_t mutex; void MyInitFunction() { pthread_mutex_init(&mutex, NULL); } void MyLockingFunction() { pthread_mutex_lock(&mutex); // Do work. pthread_mutex_unlock(&mutex); }
我想最简单的方法是使用 GCD
关于ios - 在 Alamofire 中一次只处理一个请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40416504/