在一段时间后超时NSThread

时间:2010-03-18 21:43:06

标签: iphone timeout nstimer 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
}

非常感谢您提供的任何帮助。

谢谢,

Zen_silence

2 个答案:

答案 0 :(得分:2)

使用NSOperation而不是使用NSThread。然后,您可以保留对操作的引用,并将NSTimer设置为10秒。如果计时器触发,请告诉操作取消它。

答案 1 :(得分:1)

尝试这样的事情:

workerThread = [[NSThread alloc] initWithTarget:self selector:@selector(someFunction) object:nil];
[workerThread start];
timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:workerThread selector:@selector(cancel) userInfo:nil repeats:NO];

确保你(1)在线程结束时检查workerThread.isCancelled以查看线程是否超时,以及(2)如果线程没有超时则调用[timoutTimer invalidate]来清理定时器