Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

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

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

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

 [currentThread start];

This currentThread is the pointer of AppDelegate. I have one button on my view and when i will press it I want to cancel or stop the execution of background thread.

To do This something like this:

-(void)cancelTheRunningTasks {

   if(self.currentThread !=nil) {

        [currentThread cancel];
        NSLog(@"IsCancelled: %d",[currentThread isCancelled]);   //here Yes returns
        [self removeNetworkIndicatorInView:backUpViewController.view];
    }  
}

Problem with that the background thread is still under execution.

With my thread refrence how to cancel/stop execution/kill the background thread from main thread ?

please refer some solutions. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...