GCD 串行队列未按顺序返回

GCD Serial Queue not returning in order

我不明白为什么第二个函数在第一个之前返回。这是我的代码。我想念一些简单的东西。

let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)

dispatch_async(queue) {
  self.requestToServer()
  self.sayHello()
    dispatch_async(get_main_queue(), {
        // Update the UI... 
    }
}

requestToServer() 函数显然比 sayHello() 函数花费的时间更长,但他们不应该用我创建的串行队列一次执行一个吗?我在这里做错了什么?

您误解了串行队列的概念。串行队列保证块将按照您添加它们的顺序执行。它不控制同一块内的语句。该块可以在其所有语句完成之前结束。

如果我把你的街区描述为铁路支线,它看起来像这样:

     (another queue)  -- requestToServer() ---------------------------
                     /                                  
(serial queue) start ------- sayHello() ----
                                            \
                                (main queue) --- Update the UI

requestToServer() 在您更新 GUI 之前没有机会完成。

相反,重写您的 requestToServer() 以获取完成处理程序:

func requestToServer{completion: () -> Void) {
    let session = NSURLSession(configuration: ...)
    let task = session.dataTaskWithURL(url) { data, response, error in
        // check the response from server
        ...

        // when everything is OK, call the completion handler
        completion()
    }
    task.resume()
}

self.requestToServer() {
    self.sayHello()
    dispatch_async(get_main_queue()) {
        // Update the UI... 
    }
}