Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

65
Visualizações
Need help to understand the order of execution in conjunction with async and await

With the sample code below I have made a test to understand the async and await mechanism in Swift. The sequence of processes is achieved. My test prints to the console do appear in the intended sequence (step 1-4). However, what puzzles me is that the test messages, which shall appear on the UI, do not show up in the intended sequence. Both messages (Message1 and Message2) appear together at the end of the entire process after step 4. So why does Message1 not appear right after step 1 as coded?

import UIKit

class ViewController: UIViewController {
    
    var testasyncDone = false
    @IBOutlet weak var MyButton2: UIButton!
    @IBOutlet weak var Message1: UITextField!
    @IBOutlet weak var Message2: UITextField!
    
    @IBAction func MyButton2pressed(_ sender: UIButton) {
        print("MyButton Pressed step 1")
        
        // This first message shall appear right after the button
        // is pressed
        Message1.text =  "In Button action - start"
        
        // The async task is defined and started
        testasyncDone = false
        Task.detached {
            await self.testasync()
            print("MyButton Pressed step 4")
        }
        
        // The intention of the next lines is to hold the
        // processing of the main thread until the async task is
        // completed.
        var count = 0
        repeat {
            count = count + 1
            usleep(100000)
            print (count)
        } while testasyncDone == false && count < 100
        
        // After the async task is done, the second message shall show up
        Message2.text = "In Button action - end"
    }
    
    func testasync() async {
        print("in testasync step 2")
        sleep(2)
        print("in testasync step 3")
        testasyncDone = true
    }
}
over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda