gpt4 book ai didi

ios - 限制 iOS 应用中的 dispatch_async 任务时间

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

我使用 dispatch_async 进行一些服务器调用。有时,由于互联网连接速度较慢,此调用会花费很长时间。

我如何设置以秒为单位的限制 - 例如:任务有 3 秒要完成,否则它会停止。

最佳答案

作为MultiColour Pixel says ,你真的应该为此使用 NSURLSession

但是,如果您仍在寻找 GCD 答案,这里是...


您可以轻松地使用信号量为您的请求实现超时。

您只需要创建一个初始值为 0 的信号量,然后使用 dispatch_semaphore_wait 等待网络任务完成时发出信号,或者请求超时。

因此,如果您的网络任务是同步的,您会想要做这样的事情......

let queue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL) // your GCD queue

...

dispatch_async(queue, {

let semaphore = dispatch_semaphore_create(0) // create semaphore

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.doNetworkTask()
dispatch_semaphore_signal(semaphore); // signal semaphore on completion
})

let timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(3.0 * Double(NSEC_PER_SEC))) // 3 second time-out
let returnValue = dispatch_semaphore_wait(semaphore, timeout)

guard returnValue == 0 else { // return value is non-zero if the request timed out

// request timed out, cancel the request here.
self.stopNetworkTask()
return // prevent further execution if network task was unsucessful
}

dispatch_async(dispatch_get_main_queue(), {
// do processing after request success
})

})

或者如果您的网络任务是异步的...

let queue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL) // your GCD queue

...

dispatch_async(queue, {

let semaphore = dispatch_semaphore_create(0) // create semaphore

self.doNetworkTaskWithCompletion({
dispatch_semaphore_signal(semaphore); // signal semaphore on completion
})

let timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(3.0 * Double(NSEC_PER_SEC))) // 3 second time-out
let returnValue = dispatch_semaphore_wait(semaphore, timeout)

guard returnValue == 0 else { // return value is non-zero if the request timed out

// request timed out, cancel the request here.
self.stopNetworkTask()
return // prevent further execution if network task was unsucessful
}

dispatch_async(dispatch_get_main_queue(), {
// do processing after request success
})

})

关于ios - 限制 iOS 应用中的 dispatch_async 任务时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35365942/

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