Skip to content

Instantly share code, notes, and snippets.

@olbrichj
Last active March 17, 2021 09:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olbrichj/b0ba51fa274df114c98f4744aa813c38 to your computer and use it in GitHub Desktop.
Save olbrichj/b0ba51fa274df114c98f4744aa813c38 to your computer and use it in GitHub Desktop.
func executeOnMain() {
if !Thread.isMainThread {
DispatchQueue.main.async(execute: {() -> Void in
executeOnMain()
})
return
}
// do something
}
@AlessioAnesa
Copy link

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

updated. sry it took so long

@dvalenzuela-com
Copy link

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