What are the differences between DispatchQueue schedule(), DispatchQueue async() and DispatchQueue concurrentPerform()?
Under what circumstances will it be more appropriate to use each?
I could not find much resource that says the difference between these three.
I went through these: Links: schedule, concurrentPerform, async, Raywenderlich, AppCoda , EonCodes and few others.
The async
is just for asynchronously dispatching a task to a queue (running it as soon as the queue can). It is used to dispatch some block of code to another queue. For example, one might call it from the main thread it to dispatch computationally expensive code off to some background queue, to avoid blocking the main thread. Or, if you are already on a background queue, you use it to dispatch code that must run on the main thread back to the main queue (e.g., UI updates). You can also use asyncAfter
if you want to specify when this dispatched task should run (e.g., after a specified time/delay).
The schedule
is an API that largely serves the same purpose as async
/asyncAfter
, but was introduced with Combine in iOS 13. It just dispatches blocks of code to run on the specified queue, optionally with some delay (or other constraints). If you need to support older iOS versions before iOS 13, just use async
/asyncAfter
instead. But if you are supporting contemporary iOS versions (especially if you are using Combine), then you can use this API if you want.
The concurrentPerform
serves a very different functional need, namely if you are for dispatching a block of code repeatedly and in parallel to as many worker threads as your device can support. It is often used when writing computationally intense and massively parallelized routines. It is uniquely well suited for solving those cases where you might otherwise have “thread explosion”. (The number of worker threads that can be used at any given moment at time is quite limited and if you exceed this, your app can deadlock if you accidentally “explode” how many threads you are trying to use at any moment in time.) So for example, if you want to run hundreds or thousands of iterations, in parallel, concurrentPerform
automatically constrains the degree of concurrency to the capabilities of your device (e.g. if you have 8 cores in your device, it only runs a maximum of 8 concurrent tasks at any given time). Think of this as a for
loop where the various iterations run in parallel with each other. But unless you are writing massively parallelized code, you might not need to ever use this. But when you are, it is extremely useful.