且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在IOS中取消/退出/停止线程对象或后台运行的线程的执行

更新时间:2023-11-14 14:28:04

我解决了这个问题.正是我想要做的就是我想从我的主线程或其他线程中停止或终止某些后台线程的工作条件.当我阅读Apple文档和一些帖子时,我得出结论,我们不能从另一个线程中杀死一个线程,因为它们所有线程共享公共内存空间和资源,并且由另一个线程杀死线程并不是更好(但是一个进程可以杀死另一个进程,因为两个进程之间没有公共内存空间共享).然后我得到信息,我们不能像那样退出/杀死线程,但我们仍然可以从其他线程设置正在运行的线程的取消属性.(在用户请求取消任务的代码中).

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

所以在这里我们可以设置取消属性.在我们正在执行的后台任务代码中,只需检查是否设置了取消属性.(我们需要在一段代码执行后进行监控).如果设置了取消属性/是,则在该后台线程代码中调用 [Thread exit] 并释放该线程分配的所有内存以保护内存泄漏(自动释放池不会在此处释放资源).

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.