How to cancel/exit/stop execution of Thread object or thread running in background in IOS

17,069

Solution 1

I resolved the Problem. Exactly what I was want to do that I want to stop or kill the working condition of some background thread from my main Thread or some other thread. As I read the Apple documentation and some posts I concluded that we can't kill one thread from other thread because they all threads shares common memory space and resources and its is not better to kill the thread by other thread (But one process can kill the other process because no common memory space shares between two processes). Then I got info we cant exit/kill thread like that but still we can set the cancel property of the running thread from other thread. (In code where user requested to cancel the Tasks).

So here we can set cancel property. And inside our background task code which is under execution just check whether the cancel property is set or not. (we need to monitor after a chunk of execution of code). If cancel property is set/Yes then call [Thread exit] in that background thread code and release all the memory allocated by that thread to protect memory leaks (autorelease pool will not take care here for freeing the resources).

This is How i resolved the problem.

In simple --> just set the property of the particular task u want to cancel as cancel set. (method to set cancel will be call by the thread object reference).

 if(self.currentThread != nil && [currentThread isExecuting])
   {
      [currentThread cancel];
   }

And then monitoring in your code for cancel property. If property set then exit the thread.

if([appDelegate.currentThread isCancelled])
 {
      [NSThread exit];
 }

If someone has better solution than this please refer. Otherwise It will also work fine.

Solution 2

Your background thread needs to check to see if it has been cancelled, either through the isCancelled method...

if ([[NSThread currentThread] isCancelled]) {
    // do cleanup here
    [NSThread exit];
}

You can't kill the thread externally because there is no way to know what state the thread might be in and, thus, killing it would produce indeterminate behavior (imagine if the thread was holding a mutex down in the allocator when it was killed... ouch).

Solution 3

cancel
Changes the cancelled state of the receiver to indicate that it should exit.

exit
Terminates the current thread.

Check NSThread Class Reference

For more information about cancellation and operation objects, see NSOperation Class Reference.

Note: In OS X v10.6, the behavior of the cancel method varies depending on whether the operation is currently in an operation queue. For unqueued operations, this method marks the operation as finished immediately, generating the appropriate KVO notifications. For queued operations, it simply marks the operation as ready to execute and lets the queue call its start method, which subsequently exits and results in the clearing of the operation from the queue.

Share:
17,069
iDevAmit
Author by

iDevAmit

IOS Application Developer

Updated on June 14, 2022

Comments

  • iDevAmit
    iDevAmit about 2 years

    I am detaching a thread to do some operation in the background, refer the code as below

     currentThread = [[NSThread   alloc]initWithTarget:contactServiceselector:@selector(requestForContactBackup:)object:msisdn];
    
     [currentThread start];
    

    This currentThread is the pointer declared in AppDelegate. I have a button on my view, on tap of it, the execution of background thread should stop. Refer the below code:

    -(void)cancelTheRunningTasks {
        
       if(self.currentThread !=nil) {
    
            [currentThread cancel];
            NSLog(@"IsCancelled: %d",[currentThread isCancelled]);   //here Yes returns
            [self removeNetworkIndicatorInView:backUpViewController.view];
        }  
    }
    

    Problem with the below code is that the background thread is still remains in execution.

    My question would be, having the thread reference, how to cancel/stop execution/kill the background thread from main thread?

    please suggest me possible solution. Thanks.

  • iDevAmit
    iDevAmit over 11 years
    I already tried with exit also. where I have written above function to kill/exit the thread if there I m using [NSthread exit] it is not working instead of expected results the UI is blocking. Because this works on main thread and we tried to stop the main thread. And we need to release all the resource which we allocated in our code. because after thread the auto-release will not remain responsible for release all the resources. My background task is working in some other service class,, now how to release these resources during the cancellation or exit/kill the thread.
  • Parag Bafna
    Parag Bafna over 9 years
    @Rajneesh071 exit is class method. you can not call [yourThread exit];