Reputation: 12272
So when using dispatch_async ...
Say you're making a network connection for example...
dispatch_queue_t otherQ = dispatch_queue_create(NULL, 0);
__weak MyClass *myself = self;
dispatch_async(otherQ,
^{
myself.searchResultsRA = [myself dataFrom:happyUrl ifError:nil];
dispatch_async(dispatch_get_main_queue(), ^{ if (after) after(); });
});
dispatch_release(otherQ);
Notice I am creating a queue "right there" for that call.
So, every call like that in the app, simply creates its own queue "there and then" to use.
Alternately, you can just create one queue as a global for your app, and keep it around, and always use that one same queue. (I guess, you'd really "never release it" it would just persist for the life of the app.)
(Note - I am not talking about Apple's "global queue" ..dispatch_get_global_queue .. nothing to do with that .. I simply mean you can create your own one queue and always use that same queue.)
I've never really understood if one approach is preferred or if there are dangers associated with either, or any other issues.
In short, which approach to use?
Upvotes: 3
Views: 382
Reputation: 119031
In addition to the answer from @Catfish_Man, consider that you currently have no control over how many downloads you're running concurrently and that you have no ability to cancel the downloads if the user changes their mind. Do you really want to make the user wait for one thing before requesting another, or risk flooding the network with requests and having them all fail?
In general, should you really be using GCD, or should you really opt for the higher level NSOperationQueue
APIs.
Ising GCD directly, while it may offer the 'minimum code to write', does come with drawbacks/compromises and you should make yourself aware of them before using that approach.
Upvotes: 1
Reputation: 41831
These alternatives accomplish very different things. If you create a new queue each time, then all of them can run at once. If you always use the same (serial; doesn't apply to concurrent ones) queue, the blocks on it will run one at a time in order.
You would typically use the latter in either of two situations:
To protect something that's not threadsafe from being used from more than one thread at once (most common use of serial queues)
To intentionally reduce the amount of concurrency in your app to conserve resources (whether that be memory, or server connections, or what).
Upvotes: 3