我有一些函数,可能需要很长时间才能完成。如果需要的时间超过特定时间,我希望函数停止继续。我该如何实现呢?我试过下面的解决方案,但它不会停止执行。
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*/
}
试试这个
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)
{
}