本文介绍了Swift 等待关闭线程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个由 SPM 创建的非常简单的 swift 项目,其中包含 Alamofire.

I'm using a very simple swift project created with SPM where it includes Alamofire.

main.swift:

main.swift:

import Alamofire

Alamofire.request("https://google.com").responseString(queue: queue) { response in
            print("\(response.result.isSuccess)")
}

如果我不使用锁,闭包就不会被执行.有没有办法指示在退出之前等待所有线程或特定线程?

The closure is never executed if I don't use a lock.Is there a way to instruct to wait for all threads or that specific thread before exiting?

我知道使用 Playgrounds 可以轻松实现这一点.

I'm aware this can be easily achieved using Playgrounds.

推荐答案

等待异步任务的最简单方法是使用信号量:

Simplest way to wait for an async task is to use a semaphore:

let semaphore = DispatchSemaphore(value: 0)

doSomethingAsync {
    semaphore.signal()
}

semaphore.wait()

// your code will not get here until the async task completes

或者,如果您正在等待多个任务,您可以使用一个调度组:

Alternatively, if you're waiting for multiple tasks, you can use a dispatch group:

let group = DispatchGroup()

group.enter()
doAsyncTask1 {
    group.leave()
}

group.enter()
doAsyncTask2 {
    group.leave()
}

group.wait()

// You won't get here until all your tasks are done

这篇关于Swift 等待关闭线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 23:20