杀死一个线程或替代方案
有什么方法可以通过以下方式杀死线程生成:
[NSThread detachNewThreadSelector:@selector(serverFetchInThread) toTarget:self withObject:nil];
我正在处理的场景是,在我的主线程中,我让用户在搜索栏中输入数据,并且用户输入的内容我需要发送到服务器以在单独的线程。现在,如果用户通过删除旧数据并输入新数据来更改他的选择,我不希望前一个线程浪费时间,杀死它并生成一个包含新数据的新线程。
有没有其他更好的方法来处理这种情况,请指导我。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,没有办法从另一个线程杀死一个线程。这是有充分理由的,因为没有办法以一种方式来杀死目标线程而不会有应用程序崩溃的风险。
直接回答您的问题;你需要有某种标志来指示线程它应该停止正在做的事情并退出。
然而,你的问题提出了几个问题:
首先,为什么你使用线程而不使用 GCD?通过 GCD 或 NSOperation 进行并发是解决此类问题的普遍推荐方法。
其次,如果您正在与服务器通信,您是否使用 HTTP(大多数情况下都是这种情况)?如果是这样,为什么不直接使用NSURL之类的异步特性呢?
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?
好好看看如何使用
NSOperationQueue
。您可以将 NSOperation 子类化以封装服务器通信,甚至使该队列串行(最大操作数 = 1)。
如果服务器操作尚未完成并且用户已生成更多输入,您可以取消现有操作并添加新操作。
由于
NSOperation
包装连接的效果,您可以只使用简单的同步版本并保持连接处理非常简单。另外值得一提的是兼容性。我更喜欢使用 GCD 和块,但为了兼容性,需要
NSOperationQueue
。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.