You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何两个async let调用无法并行执行?

关于async let无法并行执行及应用崩溃的问题

我看到一段关于Swift并发的说明:

相比之下,如果将两个Task初始化器都改为Task.detached,你会看到“In Task 1”和“In Task 2”混合输出,因为两者会同时执行。

我把对应的逻辑改成用async let调用,但这段代码无法实现并行执行:

输入图片描述

struct ContentView: View {
    var body: some View {
        Task {
            async let result =  runForLoop1()
            async let result2 =  runForLoop2()
        }
        
        return Text("Hello, world!")
    }
}

func runForLoop1() async -> Int {
    for i in 1...1000 {
        print("In Task 1: \(i)")
    }
    return 100_000
}

func runForLoop2() async -> Int {
    for i in 1...1000 {
        print("In Task 2: \(i)")
    }
    return 100_000
}

我使用的是Xcode Version 13.2.1 (13C100)


编辑

我尝试在Mac控制台应用中运行示例代码,但应用崩溃了:

输入图片描述

Task {
    async let result =  runForLoop1()
    async let result2 =  runForLoop2()
}

func runForLoop1() async -> Int {
    var i = 0
    let start = Date()
    while Date().timeIntervalSince(start) < 1 {
        print("In Task 1: \(i)")
        i += 1
    }
    return 100_000
}

func runForLoop2() async -> Int {
    var i = 0
    let start = Date()
    while Date().timeIntervalSince(start) < 1 {
        print("In Task 2: \(i)")
        i += 1
    }
    return 100_000
}

编辑2

我还尝试在macOS标准应用中运行同样的示例,应用依然崩溃:

输入图片描述

struct ContentView: View {
    var body: some View {
        
        Task {
            async let result =  runForLoop1()
            async let result2 =  runForLoop2()
            await print(result, result2)
        }
        
        return Text("Hello, world!")
            .padding()
    }
}

func runForLoop1() async -> Int {
    var i = 0
    let start = Date()
    while Date().timeIntervalSince(start) < 1 {
        print("In Task 1: \(i)")
        i += 1
    }
    return 100_000
}

func runForLoop2() async -> Int {
    var i = 0
    let start = Date()
    while Date().timeIntervalSince(start) < 1 {
        print("In Task 2: \(i)")
        i += 1
    }
    return 100_000
}

内容的提问来源于stack exchange,提问作者MaxFactorHub

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 00:09:51