开发者

How to properly shut down/restart NSThread after applicationDidEnterBackground/applicationWillEnterForeground

开发者 https://www.devze.com 2023-01-17 07:57 出处:网络
For performance reasons, I instantiate a dedicated NSThread to process incoming messages that are streamed from a network server.I use an NSOperation for the purpose of instantiating the connection an

For performance reasons, I instantiate a dedicated NSThread to process incoming messages that are streamed from a network server. I use an NSOperation for the purpose of instantiating the connection and receiving incoming data through the NSURLConnection delegates, but as soon as new data comes in and gets parsed, I offload the processing of the message to the dedicated NSThread. The idea is to let one thread focus on receiving incoming messages and let the other thread ju开发者_开发技巧st do the processing.

What's the proper way to shut down the NSThread when the applicationDidEnterBackground comes in?

Also, how should I restart the NSThread when applicationWillEnterForeground comes in?

Other than the main thread, it seems the state of other background threads is not maintained between going to sleep and restarting.

By the way, I'm all for using NSOperations for most tasks that have a measurable amount of work -- ie, accessing a resource over the network, performing a calculation, etc. However, in this case, I need to process messages on the fly on a long-living dedicated thread that is always there by calling performSelector:onThread:withObject:waitUntilDone: and passing it the target thread. It seems NSOperation isn't a good fit for this. I would appreciate your input.


"For performance reasons"?

  • If processing doesn't take much time, run everything (including NSURLConnection) on the main thread. Concurrency bugs are a major pain.
  • If you want things to run serially, you can emulate a "single thread" with an NSOperationQueue with maxConcurrentOperations = 1. I'm pretty sure that NSOperationQueue uses thread pools (and on 4.0, GCD, which probably uses thread pools), which means you don't need to keep a thread running all the time.

Apart from that, your process is automatically suspended and resumed by the system, so you don't need to kill off threads.

I'm not sure what you mean by "the state of other background threads".

0

精彩评论

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

关注公众号