在一定时间后使 NSThread 超时
我有一个 NSThread,我想在一段时间后超时。
[NSThread detachNewThreadSelector:@selector(someFuntion) toTarget:self withObject:nil];
- (void) someFunction {
//Some calculation that might take a long time.
//if it takes more then 10 seconds i want it to end and display a error message
}
如果您能就此提供任何帮助,我们将不胜感激。
谢谢,
禅宗沉默
I have a NSThread that i would like to timeout after a certain amount of time.
[NSThread detachNewThreadSelector:@selector(someFuntion) toTarget:self withObject:nil];
- (void) someFunction {
//Some calculation that might take a long time.
//if it takes more then 10 seconds i want it to end and display a error message
}
Any help you can provide on this would be greatly appreciated.
Thanks,
Zen_silence
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要使用 NSThread,而是使用 NSOperation。然后,您可以保留对该操作的引用,并将 NSTimer 设置为 10 秒。如果计时器触发,请告诉操作自行取消。
Instead of using NSThread, use NSOperation. You could then keep a reference to the operation, and set a NSTimer for 10 seconds. If the timer fires, tell the operation to cancel itself.
尝试这样的操作:
确保 (1) 在线程完成时检查
workerThread.isCancelled
以查看线程是否超时,并且 (2) 调用[timoutTimer invalidate]
> 如果线程没有超时则清理计时器。Try something like this:
Be sure that you (1) check
workerThread.isCancelled
when the thread finishes to see whether the thread timed out, and (2) call[timoutTimer invalidate]
to clean up the timer if the thread did not time out.