杀死线程或替代方法 [英] Killing a thread or an alternative

查看:73
本文介绍了杀死线程或替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以杀死通过以下方式产生的线程:

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.

推荐答案

不,没有办法从另一个线程中杀死一个线程。并有充分的理由,因为没有一种方法可以杀死目标线程而不会导致应用程序崩溃的方式。

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:

首先,为什么要使用线程而不使用GCD?通常建议通过GCD或NSOperation进行并发来解决此类问题。

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

其次,如果您正在与服务器通信,是否使用HTTP(大多数情况下,是这种情况)?如果是这样,为什么不直接使用NSURL和朋友的异步功能呢?

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?

这篇关于杀死线程或替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆