且构网

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

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

更新时间:2023-11-14 15:05:52

我解决了问题。正是我想做的事情,我想停止或从我的主线程或其他线程中杀死一些后台线程的工作条件。当我阅读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).

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

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.