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

后端 未结 3 1944
有刺的猬
有刺的猬 2020-12-10 09:50

I detaching The thread as given below to do some operation in background

 currentThread = [[NSThread   alloc]initWithTarget:contactServiceselector:@selector(         


        
3条回答
  •  北海茫月
    2020-12-10 10:28

    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.

提交回复
热议问题