在一定时间后使 NSThread 超时

发布于 2024-08-25 16:13:53 字数 362 浏览 9 评论 0原文

我有一个 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
}

如果您能就此提供任何帮助,我们将不胜感激。

谢谢,

禅宗沉默

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

缺⑴份安定 2024-09-01 16:13:53

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

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.

近箐 2024-09-01 16:13:53

尝试这样的操作:

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] > 如果线程没有超时则清理计时器。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文