SwiftUI DispatchQueue asyncAfter在执行十个预定任务后将无法正常工作 [英] SwiftUI DispatchQueue asyncAfter stops working correctly after ten scheduled tasks

查看:72
本文介绍了SwiftUI DispatchQueue asyncAfter在执行十个预定任务后将无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行下面的代码,它会正确计数到10,然后跳过每个奇数.

If I run the code below, it counts correctly to 10 and then skips every odd number.

如果让它运行超过20,它将开始越来越多地跳过(输出将类似于1-2-3-4-5-6-7-8-9-10-12-14-16-18-20-23-26-29 ...).

If you let it run beyond 20, it will start skipping more and more (the output will be like 1-2-3-4-5-6-7-8-9-10-12-14-16-18-20-23-26-29 ...).

找不到相关文档,例如计划任务的数量有限,所以请问您:)从昨天开始学习SwiftUI,请原谅这是一个明显的问题.

Couldn't find documentation of e.g. a limit of scheduled tasks, so asking you :) Learning SwiftUI since yesterday, so pardon if it's an obvious question.

如果将其安排在与main不同的DispatchQueue中,则没有任何区别.

If it's scheduled in a different DispatchQueue than main, it makes no difference.

感谢您的帮助!

import SwiftUI

struct ContentView: View {
    @State private var counter : Int = 0
    
    func buttonTap() {
        let time : DispatchTime = .now()
        
        var delay : Double = 0
        
        for _ in 1...50 {
            
            delay = delay + 0.2
            
            DispatchQueue.main.asyncAfter(deadline: time + delay) {
                counter += 1
            }
            
        }
    }
    
    var body: some View {
        ZStack {
            
            Color(.black)
                .edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
            
            Text(String(counter))
                .foregroundColor(.green)
                .padding()
            
            Text("Button")
                .foregroundColor(.green)
                .offset(y: 50)
                .onTapGesture(perform: {
                    buttonTap()
                })
            
        }
    }
}

推荐答案

这是一种奇怪的行为,甚至在事件之间的间隔时间更长(例如2秒).

That is an odd behavior, and it even occurs for much longer time intervals between events (for example, 2 seconds).

考虑改用 Timer :

您可以使用多个单独的启动计时器,它们的工作方式与单独的调度一样:

You can use multiple single fire timers that work just like your separate dispatches:

func buttonTap() {
    
    var delay : Double = 0
    
    for _ in 1...50 {
        
        delay = delay + 0.2
        
        Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { timer in
            self.counter += 1
        }
        
    }
}

或每隔 0.2 秒触发一次的单个计时器:

or a single timer that fires every 0.2 seconds:

func buttonTap() {
    Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { timer in
        self.counter += 1
        if counter == 50 {
            timer.invalidate()
        }
    }
}

这篇关于SwiftUI DispatchQueue asyncAfter在执行十个预定任务后将无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆