With dispatch_async, use your own queues or your own global queue?

So, when using dispatch_async ...

Suppose you are making a network connection, for example ...

dispatch_queue_t otherQ = dispatch_queue_create(NULL, 0);

__weak MyClass *myself = self;
     myself.searchResultsRA = [myself dataFrom:happyUrl ifError:nil];
    dispatch_async(dispatch_get_main_queue(), ^{ if (after) after(); });



Note, I am creating a "right there" queue for this call.

So every call like this in the application just creates its own there and then queue to use.

Alternatively, you can simply create one queue as global for your application and keep it and use one queue always. (I think you really "never released it", it would just keep for the life of the app.)

(Note: I'm not talking about Apple's "global queue" ... dispatch_get_global_queue .. nothing to do with it .. I just want you to be able to create your own queue and always use the same queue.)

I have never understood if any approach is preferable or if there are dangers associated with this or that problem.

In short, which one is suitable for use?


source to share

2 answers

These alternatives do completely different things. If you create a new queue every time, then they can all start at once. If you always use the same (serial, not applicable to parallel) queue, the blocks on it will run in turn.

Typically you've used the latter in either of two situations:

  • To protect something that is not thread safe from multiple or multiple threads (the most common use of sequential queues)

  • Deliberately reduce the amount of concurrency in your application to save resources (be it memory or server connections, or what).



In addition to the answer from @Catfish_Man, consider that you have no control over how many downloads you use at the same time, and that you have no way to cancel the download if the user changes their mind. Do you really want the user to wait for one thing before asking for another, or the risk of flooding the web with requests and crashing all of them?

In general, if you are really using GCD, or you really want to use a higher level API NSOperationQueue


Ising GCD directly, while it may suggest "minimal code to write", has drawbacks / tradeoffs and you should be aware of them before using this approach.



All Articles