我正在分离一个线程在后台做一些操作,引用下面的代码
currentThread = [[NSThread alloc]initWithTarget:contactServiceselector:@selector(requestForContactBackup:)object:msisdn];
[currentThread start];
这个currentThread就是AppDelegate中声明的指针。 我的 View 上有一个按钮,点击它,后台线程的执行应该停止。引用以下代码:
-(void)cancelTheRunningTasks {
if(self.currentThread !=nil) {
[currentThread cancel];
NSLog(@"IsCancelled: %d",[currentThread isCancelled]); //here Yes returns
[self removeNetworkIndicatorInView:backUpViewController.view];
}
}
以下代码的问题在于后台线程仍在执行中。
我的问题是,有了线程引用,如何从主线程取消/停止执行/杀死后台线程?
请建议我可能的解决方案。 谢谢。
最佳答案
您的后台线程需要检查它是否已被取消,或者通过 isCancelled
方法...
if ([[NSThread currentThread] isCancelled]) {
// do cleanup here
[NSThread exit];
}
你不能从外部杀死线程,因为没有办法知道线程可能处于什么状态,因此,杀死它会产生不确定的行为(想象一下,如果线程在分配器中持有一个互斥量,当它被杀了……哎哟)。
关于iphone - 如何在 IOS 中取消/退出/停止执行线程对象或在后台运行的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15413955/