How can i stop the background thread from the main thread in Iphone NSthread?

二次信任 提交于 2019-12-12 10:17:42

问题


I start a background thread from my program while my main thread is checking something. If the checking goes false, I want to stop the running background thread and start it all over again with my new parameters.

I want to stop it coz the thread will be downloading images and if I doesnt stop it and call it again, it will take a lot of time for the new images to get downloaded. Is it possible to do so?


回答1:


In my experience, its usually best to let a thread exit gracefully by itself. How about having some common variable that the main thread could set to false if things go awry. The second thread could periodically check this variable and if it has been set to false, it knows it should clean up and return.

I think you could use condition variables in a more elegant fashion, but his approach with the proper use of NSLock should work.




回答2:


NSThread implements a method -(void)cancel that sets state information in the receiving thread to indicate, it should exit. The receiving background thread should - if behaving properly - regulary check whether it is cancelled using -(BOOL)isCancelled.

This way the receiver has a chance to clean up it's acquired resources in a proper way.

Looking into the Java language thread semantic, this apparatus works quite the same way. Javas Thread implements two methods void Thread.interrupt() and boolean Thread.isInterrupted().

In case long running background operations do not react to an attempt to -cancel them, i would see this as an serious problem and file a bug report / change request.

You may wait on the termination of the background thread by regulary calling either -(BOOL)isFinished or -(BOOL)isExecuting on the background NSThread. Unfortunately the NSDidBecomeSingleThreadedNotification is not supported on the iPhone plattform.



来源:https://stackoverflow.com/questions/2069783/how-can-i-stop-the-background-thread-from-the-main-thread-in-iphone-nsthread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!