How to properly disable / restart NSThread after applicationDidEnterBackground / applicationWillEnterForeground

For performance reasons, I create a special NSThread to handle incoming messages that are sent from a network server. I use NSOperation to create a connection instance and receive incoming data through the NSURLConnection delegates, but as soon as new data arrives and is parsed, I upload the message processing to the dedicated NSThread. The idea is to allow one thread to focus on receiving incoming messages and let the other thread just do the processing.

What is the correct way to disable NSThread when a DidEnterBackground application logs in?

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

Besides the main thread, it seems that the state of other background threads is not supported between going to sleep and restarting.

By the way, I all use NSOperations for most tasks that have a measurable amount of work, i.e. access to the resource over the network, performing calculations, etc. However, in this case, I need to process messages on the fly on a long-living dedicated thread that always exists by calling the executeSelector: onThread: withObject: waitUntilDone: function and passing the target thread to it. NSOperation doesn't seem to be suitable for this. I would appreciate your input.

+4
source share
1 answer

"For performance reasons"?

  • If processing does not take much time, run everything (including NSURLConnection) in the main thread. Concurrency errors are a major pain.
  • If you want everything to run in serial, you can emulate a "single thread" with NSOperationQueue with maxConcurrentOperations = 1 . I am sure that NSOperationQueue uses thread pools (and on 4.0, GCD, which probably uses thread pools), which means you don't need to constantly maintain a thread.

In addition, your process is automatically paused and resumed by the system, so you do not need to kill threads.

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

0
source

All Articles