开发者

how to stop nsthread

开发者 https://www.devze.com 2023-02-15 06:41 出处:网络
I am using a thread to update messages in background in my application. The thread is started in my messages class.

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
  开发者_C百科              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.


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


( 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 exit];

Have you checked this method of NSThread class.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消