Skip to content

Instantly share code, notes, and snippets.

@olbrichj
Last active Mar 17, 2021
Embed
What would you like to do?
func executeOnMain() {
if !Thread.isMainThread {
DispatchQueue.main.async(execute: {() -> Void in
executeOnMain()
})
return
}
// do something
}
@AlessioAnesa
Copy link

AlessioAnesa commented Jan 5, 2018

doesn't this need a return in the if block?
Otherwise, in case of code executing outside the main thread, the // do something part will be executed 2 times.

@olbrichj
Copy link
Author

olbrichj commented Oct 31, 2018

updated. sry it took so long

@dvalenzuela-com
Copy link

dvalenzuela-com commented Nov 26, 2018

It is still wrong. It should read:

func executeOnMain() {
  if !Thread.isMainThread {
    DispatchQueue.main.async(execute: {() -> Void in
      executeOnMain()
    })
    return
  }
  
  // do something
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment