在完成下面列出的漫长过程的设定时间限制后,是否有一种好方法可以调用外部方法?我希望漫长的过程在设定的时间间隔后停止尝试并调用方法来尝试其他内容并结束请求。
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//// LONG PROCESS
dispatch_async(dispatch_get_main_queue(), ^{
//// RESULTS PROCESS
});
});
答案 0 :(得分:4)
为了杀死"在运行您的区块的过程中,您必须检查条件。这将允许您进行清理。请考虑以下修改:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
BOOL finished = NO;
__block BOOL cancelled = NO;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
if (!finished) {
cancelled = YES;
}
});
void (^cleanup)() = ^{
// CLEANUP
};
//// LONG PROCESS PORTION #1
if (cancelled) {
cleanup();
return;
}
//// LONG PROCESS PORTION #2
if (cancelled) {
cleanup();
return;
}
// etc.
finished = YES;
dispatch_async(dispatch_get_main_queue(), ^{
//// RESULTS PROCESS
});
});
答案 1 :(得分:2)
在////Long Process
完成后,将布尔值(如BOOL finished
)更改为true
。
在您在此处输入的dispatch_async(...)
来电之后,请添加以下内容:
int64_t delay = 20.0; // In seconds
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC);
dispatch_after(time, dispatch_get_main_queue(), ^(void){
if (!finished) {
//// Stop process and timeout
}
});
这样,在20秒后(或任何你想要的时间),您可以检查过程是否仍在加载并采取一些措施。
答案 2 :(得分:0)
我已经将此方法用于Swift:
let delay = 0.33 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
//// RESULTS PROCESS
}