Killing a thread or an alternative

故事扮演 提交于 2019-12-24 11:27:44

问题


Is there any way I can kill a thread spawn through:

[NSThread detachNewThreadSelector:@selector(serverFetchInThread) toTarget:self withObject:nil];

The scenario I am working on is that in my main thread I am letting user enter data in my search bar and what ever user is typing I need to send to server for searching in a separate thread. Now, if user changes his selection by deleting old data and entering new data I do not want the previous thread to waste its time, kill it and spawn a new thread with new data.

Be there any other better way to handle this situation, please guide me.


回答1:


No, there is no way to kill a thread from another thread. And for good reason as there is no way to do so in a fashion where the targeted thread is killed without risk of crashing the app.

To directly answer your question; you need to have some kind of a flag that indicates to the thread that it should stop doing whatever it is doing and exit.

However, a couple of questions are raised by your question:

First, why are you using threads and not using GCD? Concurrency via GCD or NSOperation is the generally recommended way to solve such problems.

Secondly, if you are talking to a server, are you using HTTP (most of the time, that is the case)? If so, why not directly use the asynchronous features of NSURL and friends?




回答2:


Have a good look at using NSOperationQueue.

You can subclass NSOperation it to wrap up your server communications, and even make that queue serial (maximum operations = 1).

If a server operation is not yet finished and user has generated more input, you can cancel the existing one, and add the new one.

Due to the effect of the NSOperation wrapping your connection, you can just use the simple synchronous version and keep the connection handling very straightforward.

Also worth mentioning is compatibility. I would prefer to use GCD and blocks, but for compatibility, NSOperationQueue is required.



来源:https://stackoverflow.com/questions/5443858/killing-a-thread-or-an-alternative

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