Tom Hamming
Tom Hamming

Reputation: 10981

GCD dispatch_async for app-lifetime task?

I've used GCD before with dispatch_async for background-threading units of work like parsing data from a network request (in, say, JSON or XML), and it's WONDERFUL. But what if I have a background task that's going to run for the length of the application? Is dispatch_async still a good fit for this case, or is there a better way to implement it?

Upvotes: 0

Views: 185

Answers (2)

Ben Zotto
Ben Zotto

Reputation: 71048

Sure, but create your own dispatch queue for it. (If you use a global queue, you may tie up that queue--or one of its threads--forever.)

dispatch_queue_t dispatchQueue = dispatch_queue_create("com.mycompany.myapp.ForeverOperation", DISPATCH_QUEUE_SERIAL);
dispatch_async(dispatchQueue, ^{
    // worker routine 
});

More traditionally, you would create an explicit thread for this, and if it will run forever, that might make more "sense". But the results are basically the same.

NSThread * myWorkerThread = [[NSThread alloc] initWithTarget:...
[myWorkerThread start];

If you need to communicate with other threads/queues, as always, standard synchronization techniques may be required.

Upvotes: 3

matt
matt

Reputation: 535616

This really has nothing to do with dispatch_async, which is merely one approach to doing something in a background thread. If you want to do something in a background thread, do it in a background thread! Just be aware that doing this constantly can be a drag on your app, since you've only got so much processing time and only so many processors; you may end up having to study that in Instruments. You might want to break up your task into little bits and do it in short chunks every so often. Both GCD and NSOperation can help with that.

Upvotes: 1

Related Questions