swift 串行队列操作乱序
swift serial queue operations out of order
我正在尝试实现一个串行队列,但由于某种原因,第二个块在第一个块之前完成(如系统打印中所示。关于为什么会发生这种情况或如何修复它的任何知识都是非常感谢!
SWIFT 代码:
func didAccept(with username: String) {
let serialQueue = DispatchQueue(label: "acceptQueue")
serialQueue.async {
let url = URL(string: "http://127.0.0.1:5000/get-user-id")!
var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
request.httpMethod = "POST"
request.multipartFormData(parameters: ["username": username])
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
do {
let requestList = try JSONDecoder().decode(TempId.self, from: data)
self.friend_id = requestList.friend_id
print("first: \(self.friend_id)")
} catch let jsonErr {
print(jsonErr)
}
}
task.resume()
}
serialQueue.async {
let url2 = URL(string: "http://127.0.0.1:5000/accept-decline-request")!
var request2 = URLRequest(url: url2, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
request2.httpMethod = "POST"
request2.multipartFormData(parameters: ["user_id": "17", "friend_id": "\(self.friend_id)", "response": "accept"])
print("second: \(self.friend_id)")
let task2 = URLSession.shared.dataTask(with: request2) { (data, response, error) in
guard let data = data else { return }
}
task2.resume()
}
table.reloadData()
}
输出:
second: -1
first: 21
您可以使用操作和操作队列来满足此要求。
您可以设置
maxConcurrentOperationCount = 1
它会一次调用一个请求。因此,在您的第一个任务没有响应之前,永远不会调用第二个请求。一旦第一个请求响应到来,第二个请求将自动添加到下一个队列中。
我正在尝试实现一个串行队列,但由于某种原因,第二个块在第一个块之前完成(如系统打印中所示。关于为什么会发生这种情况或如何修复它的任何知识都是非常感谢!
SWIFT 代码:
func didAccept(with username: String) {
let serialQueue = DispatchQueue(label: "acceptQueue")
serialQueue.async {
let url = URL(string: "http://127.0.0.1:5000/get-user-id")!
var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
request.httpMethod = "POST"
request.multipartFormData(parameters: ["username": username])
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
do {
let requestList = try JSONDecoder().decode(TempId.self, from: data)
self.friend_id = requestList.friend_id
print("first: \(self.friend_id)")
} catch let jsonErr {
print(jsonErr)
}
}
task.resume()
}
serialQueue.async {
let url2 = URL(string: "http://127.0.0.1:5000/accept-decline-request")!
var request2 = URLRequest(url: url2, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
request2.httpMethod = "POST"
request2.multipartFormData(parameters: ["user_id": "17", "friend_id": "\(self.friend_id)", "response": "accept"])
print("second: \(self.friend_id)")
let task2 = URLSession.shared.dataTask(with: request2) { (data, response, error) in
guard let data = data else { return }
}
task2.resume()
}
table.reloadData()
}
输出:
second: -1
first: 21
您可以使用操作和操作队列来满足此要求。 您可以设置
maxConcurrentOperationCount = 1
它会一次调用一个请求。因此,在您的第一个任务没有响应之前,永远不会调用第二个请求。一旦第一个请求响应到来,第二个请求将自动添加到下一个队列中。