开发者

Killing a thread or an alternative

开发者 https://www.devze.com 2023-02-19 18:41 出处:网络
Is there any way I can kill a thread spawn through: [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开发者_StackOverflow社区 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:

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消