我必须执行一些操作,直到更改启动它们的开关为止。我尝试将GCD与工作项队列一起使用,认为异步操作将允许用户更改开关并因此停止操作。代码运行时,它永远不会看到甚至触发开关更改。这是我的代码。知道我在做什么错吗?
@IBaction func trailerScanSwitchChange(_ sender: Any) {
let model = Model() //Instantiate the Model
gScan = trailerScanSwitch.isOn
//Set up work iten to read and parse data
let work1 = DispatchWorkItem {
while (gScan && gConnected){
model.parseValues()
print ("parsing values")
if gScan == false || gConnected == false{
break
}
model.convertVoltsToLights()
self.updateLights()
print ("updating Lights")
if gScan == false || gConnected == false{
break
}
}
}
if trailerScanSwitch.isOn == true{
print ("Scanning")
//perform on the current thread
work1.perform()
//perpform on the global queue
DispatchQueue.global(qos: .background).async(execute: work1) // concurrent actions
return
}
else { //Stop reading and displaying
gScan = false
work1.cancel()
}
}