There's a very narrow semantic difference between the two, and I find myself wondering why both options exist. Are they in any way different functionally, or is one likely just an alias of the other?
To summarize, DispatchQueue. async allows you to schedule work to be done using a closure without blocking anything that's ongoing. In most cases where you need to dispatch to a dispatch queue you'll want to use async .
DispatchQueue. global() runs these kind of tasks in background threads. You can tell the queue about how important your task is, so that DispatchQueue can prioritize your task. You can do this by providing Quality-of-Service information.
sync means doing thing in main thread/UI thread and x. async means doing in background thread.
DispatchQueue. main (the main queue) is a serial queue. sync and async do not determine serialization or currency of a queue, but instead refer to how the task is handled. Synchronous function returns the control on the current queue only after task is finished.
There is no difference at all. They are, in fact, the very same method.
To the compiler,
myQueue.async(execute: { foo() })
is exactly the same as
myQueue.async {
foo()
}
When the last argument of any function or method is a function, you can pass that argument as a trailing closure instead of passing it inside the argument list. This is done in order to make higher-order functions such as DispatchQueue.async
feel more like part of the language, reduce syntactic overhead and ease the creation of domain-specific languages.
There's documentation on trailing closure syntax here.
And by the way, the idiomatic way to write my first example would be:
myQueue.async(execute: foo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With