Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone NSThread在一定时间后超时_Iphone_Timeout_Nstimer_Nsthread - Fatal编程技术网

Iphone 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,我想在一定时间后超时

[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
,函数应立即清理并返回。否则,线程在收到
取消
消息时不会终止。