Iphone NSThread在一定时间后超时
我有一个NSThread,我想在一定时间后超时Iphone NSThread在一定时间后超时,iphone,timeout,nstimer,nsthread,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 dis
[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使用NSOperation而不是NSThread。然后可以保留对操作的引用,并将NSTimer设置为10秒。如果计时器触发,请告诉操作自行取消。请使用NSOperation,而不是使用NSThread。然后可以保留对操作的引用,并将NSTimer设置为10秒。如果计时器启动,请告诉操作自动取消。尝试以下操作:
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]
在线程未超时时清除计时器。尝试以下操作:
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]
清除计时器。我忘了提到您需要定期检查[[NSThread currentThread]isCancelled]
在someFunction
中。如果返回YES
,函数应立即清理并返回。否则,线程在收到取消
消息时不会终止。我忘了提到您需要定期检查[[NSThread currentThread]isCancelled]
中的someFunction
。如果返回YES
,函数应立即清理并返回。否则,线程在收到取消
消息时不会终止。