如何停止nsthread
我正在使用线程在应用程序的后台更新消息。该线程在我的消息类中启动。
Messages.m
timerThread = [[NSThread alloc] initWithTarget:self
selector:@selector(startTimerThread:) object:nil];
[timerThread start];
现在我希望线程在用户注销应用程序时停止。为此,我在注销方法(在另一个类中)中添加了
Messages *msg=[[Messages alloc]init];
[msg.timerThread cancel];
[msg release];
“但即使在退出应用程序后,线程仍在运行”。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
[timerThread cancel]
不会停止线程,它只是将其标记为已取消。我认为您的startTimerThread:
执行某种无限循环。您必须定期检查此循环中的isCancelled
,如果是“是”,您应该执行一些清理操作并退出此循环。顺便说一句,如果您不经常执行更新,则在主线程中运行 NSTimer 并在回调上分离新线程会更方便(例如
[self PerformSelectorInBackground:@selector(updateMessages:) withObject:whatever ]
)或启动NSOperation
的实例。[timerThread cancel]
doesn't stop thread, it just marks it as cancelled. I presume that yourstartTimerThread:
performs some sort of infinite loop. You have to checkisCancelled
in this loop periodically and if it's YES you should perform some clean up and break from this loop.BTW if you don't perform updates frequently it is more convenient to run
NSTimer
in main thread and detach new thread on callbacks (like[self performSelectorInBackground:@selector(updateMessages:) withObject:whatever]
) or start an instance ofNSOperation
.(我在这里假设您在程序中的其他地方创建了 Messages 实例)
根据您提供的代码,您正在创建一个新的 Messages 实例作为注销过程的一部分(这会启动一个新线程),取消该新线程( -cancel 是停止线程的正确方法 - 如果您的线程方法遵循文档中列出的注意事项),然后释放您的(额外的?)Messages 实例。此时,您的原始 Messages 实例仍然存在,并且该实例的线程仍在运行。
如果您希望线程在类的实例被释放时停止,您可能应该在 -dealloc 消息方法,并确保您的原始消息实例在适当的时间。
( I am assuming here that you create an instance of Messages somewhere else in the program )
According to your provided code you are creating a new Messages instance as part of your sign out process ( which starts a new thread ), canceling that new thread ( -cancel is a proper way to stop a thread -- if your thread method follows the considerations listed in the documentation ), then releasing your ( extra? ) Messages instance. At this point your original Messages instance is still around, and the thread from that is still running.
If you want the thread to stop when the instance of the class is deallocated, you probably should take care of that in a -dealloc method on Messages and make sure your original Messages instance is released at the proper time.
你检查过 NSThread 类的这个方法吗?
Have you checked this method of NSThread class.
使用
[NSThread exit];
或[NSThread cancel];
Use
[NSThread exit];
or[NSThread cancel];