how to stop nsthread

a 夏天 提交于 2019-12-09 01:21:31

问题


I am using a thread to update messages in background in my application. The thread is started in my messages class.

Messages.m

timerThread = [[NSThread alloc] initWithTarget:self
                selector:@selector(startTimerThread:) object:nil]; 
[timerThread start];

now I want the thread to stop when the user signout of the application. For that in the signout method (in another class) I added

Messages *msg=[[Messages alloc]init];  
[msg.timerThread cancel];  
[msg release];  

But even after signing out of the application the thread is still running.


回答1:


( 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.




回答2:


[timerThread cancel] doesn't stop thread, it just marks it as cancelled. I presume that your startTimerThread: performs some sort of infinite loop. You have to check isCancelled 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 of NSOperation.




回答3:


[NSThread exit];

Have you checked this method of NSThread class.




回答4:


Use [NSThread exit]; or [NSThread cancel];



来源:https://stackoverflow.com/questions/5193062/how-to-stop-nsthread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!