2010-03-18 63 views
0

我有一段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

回答

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]清理定時器,如果線程沒有超時。

+0

該代碼不起作用,線程仍然運行到最後。 – 2010-03-18 23:30:10

+0

我忘記提及你需要定期檢查'someFunction'內的[[NSThread currentThread] isCancelled]。如果返回YES,函數應該清理並立即返回。否則,線程在接收到「cancel」消息時不會終止。 – Tom 2010-03-19 01:31:18

2

而不是使用NSThread的,使用的NSOperation。然後,您可以保留對操作的引用,並將NSTimer設置爲10秒。如果定時器觸發,請告訴操作自行取消。

+0

請輸入你的代碼,然後輸入一些代碼來顯示如何操作? – 2010-03-18 23:30:32