PerformSelector NSThread 问题

发布于 2024-10-22 12:25:11 字数 517 浏览 4 评论 0原文

在performSelector waitsUntilDone 时是否可以取消线程?

请参见下文:

我有一个 while 循环,其中包含以下行:

[self performSelector:@selector(getMyRecords:) onThread:myThread withObject:i waitUntilDone:YES]

有时,我需要在循环执行时取消线程 myThread 。我遇到以下崩溃问题:

Terminating app due to uncaught exception 'NSDestinationInvalidException', reason: '*** -[MyController performSelector:onThread:withObject:waitUntilDone:modes:]: target thread exited while waiting for the perform'

Is it possible to cancel a thread while performSelector waitsUntilDone?

See below:

I have a while loop with following line:

[self performSelector:@selector(getMyRecords:) onThread:myThread withObject:i waitUntilDone:YES]

Sometimes, I need to cancel my thread myThread while my loop executes. I get following crash issue:

Terminating app due to uncaught exception 'NSDestinationInvalidException', reason: '*** -[MyController performSelector:onThread:withObject:waitUntilDone:modes:]: target thread exited while waiting for the perform'

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

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

发布评论

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

评论(3

思慕 2024-10-29 12:25:11

如果线程内有一个长时间运行的操作,您可以声明一个条件变量(原子),例如“取消”并检查它。
像这样的东西:

- (void) threadFunc {
 while (!canceled){
   // do stuff
 }
}


- (void) cancelThread {
 canceled = true;
}

if you have a long running operation inside a thread, you can declare a condition variable (atomic) like 'canceled' and check it.
something like:

- (void) threadFunc {
 while (!canceled){
   // do stuff
 }
}


- (void) cancelThread {
 canceled = true;
}
赏烟花じ飞满天 2024-10-29 12:25:11

我认为最简单的方法是使用 NSThread's -(void)取消方法。

I think the easiest way is to use NSThread's -(void)cancel method.

命硬 2024-10-29 12:25:11

查看NSObject的文档:

此方法将消息排队
目标线程的运行循环使用
默认运行循环模式,即
与相关的模式
NSRunLoopCommonModes 常量。作为一部分
其正常的运行循环处理,
目标线程使消息出列
(假设它正在运行在其中之一
默认运行循环模式)并调用
所需的方法。

您无法取消排队的消息
使用此方法。
如果您想要
取消消息的选项
当前线程,您必须使用

执行选择器:withObject:延迟后:
或者
执行选择器:withObject:afterDelay:inModes:
方法。

此方法保留接收者并
arg 参数直到之后
执行选择器。

Check out the documentation of NSObject:

This method queues the message on the
run loop of the target thread using
the default run loop modes—that is,
the modes associated with the
NSRunLoopCommonModes constant. As part
of its normal run loop processing, the
target thread dequeues the message
(assuming it is running in one of the
default run loop modes) and invokes
the desired method.

You cannot cancel messages queued
using this method.
If you want the
option of canceling a message on the
current thread, you must use either
the
performSelector:withObject:afterDelay:
or
performSelector:withObject:afterDelay:inModes:
method.

This method retains the receiver and
the arg parameter until after the
selector is performed.

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