我有一些函数,其代码可能需要很长时间才能完成。如果需要的时间超过特定时间,我希望函数停止继续。我该如何实现呢?我尝试了以下解决方案,但它并没有停止执行。
override func viewDidLoad() {
super.viewDidLoad()
let task = DispatchWorkItem {
self.myfunction()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: {
task.cancel()
})
task.perform()
}
func myfunction() -> Void {
/*some codes that may take long time to complete*/
}
答案 0 :(得分:0)
试试这个
var stop:Bool!
override func viewDidLoad() {
super.viewDidLoad()
stop = false
let task = DispatchWorkItem {
self.myfunction()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: {
stop = true
})
task.perform()
}
func myfunction() -> Void {
if(stop)
{
// invalidate timer , break for loop or return
}
}
//更好的方法让Web服务在请求中设置超时,这里设置请求为5秒超时
let urlRequest = NSMutableURLRequest(url: newUrl! as URL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
let queue = OperationQueue()
NSURLConnection.sendAsynchronousRequest(urlRequest as URLRequest, queue: queue)
{
}