views:

228

answers:

2

Hello,

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

+2  A: 

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.

Steven Canfield
Code you please post some code showing how to do this?
Zen_silence
+1  A: 

Try something like this:

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];

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.

Tom
That code does not work the thread still runs to the end.
Zen_silence
I forgot to mention that you need to periodically check `[[NSThread currentThread] isCancelled]` within `someFunction`. If that returns `YES`, the function should clean up and return immediately. Otherwise, the thread will not terminate when it receives the `cancel` message.
Tom