[英]dispatch_async timeout method call
Is there a good way to call an external method after a set time limit for completing the long process outlined below? 在设定的时间限制后,是否有一种好的方法可以调用外部方法来完成下面概述的长过程? I would like the long process to stop trying after a set interval and call a method to try something else and wrap up the request. 我希望漫长的过程在设置的时间间隔后停止尝试,并调用方法尝试其他操作并包装请求。
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//// LONG PROCESS
dispatch_async(dispatch_get_main_queue(), ^{
//// RESULTS PROCESS
});
});
In order to "kill" the process that's running your block, you'll have to check a condition. 为了“杀死”正在运行的程序块,您必须检查条件。 This will allow you to do cleanup. 这将允许您进行清理。 Consider the following modifications: 请考虑以下修改:
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
});
});
In the ////Long Process
change a boolean value (like BOOL finished
) to true
when finished. 在////Long Process
BOOL finished
布尔值(如BOOL finished
)更改为true
。 After the call to dispatch_async(...)
you typed here, add this: 在您在此处键入对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
}
});
In this way, after 20 seconds (or any time you want) you can check if the process is still loading and take some provisions. 这样,在20秒(或您希望的任何时间)之后,您可以检查进程是否仍在加载并采取一些措施。
I've used this method for Swift: 我已经为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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.