gpt4 book ai didi

ios - 等到第一个异步函数完成后再执行第二个异步函数

转载 作者:行者123 更新时间:2023-11-28 11:13:54 25 4
gpt4 key购买 nike

我希望在调用第二个异步函数之前完成第一个异步函数

我已经试过了:

let group = dispatch_group_create();

//Execute First
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
self.LoadFirst("https://www.example.com/first.php", username: MyVariables.username as String)
});

//After Above is Finished then Execute
dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
self.LoadSecond("https://www.example.com/second.php", username: MyVariables.username as String!)
});

但是他们都在同时运行

最佳答案

您有多种选择。这里有一些:

1。使用您自己的串行调度队列:

let queue = dispatch_queue_create("com.mycompany.serial-queue",
dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0))

dispatch_async(queue) {
print("inside block 1")
}

dispatch_async(queue) {
print("inside block 2")
}

2。将 NSOperationQueue 与依赖项一起使用:

let queue = NSOperationQueue()

let op1 = NSBlockOperation {
print("inside block 1")
}

let op2 = NSBlockOperation {
print("inside block 2")
}

op2.addDependency(op1) // op2 may only execute after op1 is finished

queue.addOperation(op1)
queue.addOperation(op2)

3。使用串行 NSOperationQueue:

let queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 1 // execute 1 operation at a time

queue.addOperationWithBlock {
print("inside block 1")
}

queue.addOperationWithBlock {
print("inside block 2")
}

关于ios - 等到第一个异步函数完成后再执行第二个异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33058123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com