i don't think it is provided by the system already so i'd like to implement a smart version of DispatchQueue.async function - the one that will not reschedule the block if i am already on the queue in question and call the block directly instead in this case.
Code Block extension DispatchQueue { func asyncSmart(execute: @escaping () -> Void) { if DispatchQueue.current === self { // ????? execute() } else { async(execute: execute) } } }
the immediate problem is that there is no way to get the current queue (in order to compare it with the queue parameter and do the logic branch).
anyone've been through it and solved this puzzle?
Taking a step back, the whole goal of your proposed extension is to take you from an arbitrary context to a specific desired queue, but that goal is troublesome. A given piece of code shouldn’t need to detect this at runtime. You should know at the time of writing the code that you’re running on your desired queue. If you are, you don’t need to do anything. If you’re not, you always need to async over to that queue.
Finally, above I mentioned that you should know at the time of writing that you’re running on the desired queue. You can use a Dispatch precondition to assert that at runtime. For example:
Code Block class Example { … let queue: DispatchQueue func someFunc() { dispatchPrecondition(condition: .onQueue(self.queue)) // … rest of your code … } }
Note that this API was specifically crafted to prevent folks from falling into the dispatch_get_current_queue pitfall.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"