[英]Return function from background thread
My function execution is taking time 我的函数执行需要时间
func hasValidValues() -> Bool{
let leftValue = Double(leftTextValue) ?? 0
let rightValue = Double(rightTextValue) ?? 0
switch self.stackViewType {
let leftValid = self.hasValidValue(min: targetMin, max: targetMax, value: CGFloat(leftValue), unitConversation: true)
let rightValid = self.hasValidValue(min: 0, max: plusMinusLimit, value: CGFloat(rightValue), unitConversation: true)
return leftValid && rightValid
}
Now I need to execute this in background thread, and wanted to return so UI thread can access it and I can change UI in another controller. 现在,我需要在后台线程中执行此操作,并想返回,以便UI线程可以访问它,并且可以在另一个控制器中更改UI。
Can anyone help me on this? 谁可以帮我这个事?
Use DispatchQueue
: 使用
DispatchQueue
:
DispatchQueue.global().async {
let result = self.hasValidChanges()
DispatchQueue.main.async {
// Use result
}
}
You can't return value from another tread because each thread has its own stack. 您不能从另一个胎面返回值,因为每个线程都有自己的堆栈。 So you have to use callback here.
因此,您必须在此处使用回调。
func checkValidValues(completionHandler: @escaping ((Bool) -> Void)) {
DispatchQueue.global().async { [unowned self] in
let result = self.hasValidChanges()
DispatchQueue.main.async {
completionHandler(result)
}
}
You could use a dispatch group 您可以使用调度组
var b: Bool = false
let queue = DispatchQueue(label: "myQueue")
let group = DispatchGroup()
group.enter()
DispatchQueue.global().async {
b = hasValidValues()
group.leave()
}
group.notify(queue: queue) {
//use b
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.