I have two functions (or tasks) that I want to run one after the other and i'm using DispatchGroup to track them and notify me when they're complete. Right now they're being done in the Main thread but I want to run these tasks in a background thread. How would I go about doing so? I've tried a few approaches but they either run simultaneously or I get an exception error after the first one completes. The following code performs the tasks one after the other but if I call Thread.current inside the functions I can see that they are being run in the Main thread.
@objc func doWorkFunctions(){
taskGroup.enter()
DispatchQueue.global(qos: .background).sync {
self.firstFunction {
self.taskGroup.leave()
}
}
taskGroup.enter()
DispatchQueue.global(qos: .background).sync {
self.secondFunction {
self.taskGroup.leave()
}
}
taskGroup.notify(queue: .main) {
print("All tasks completed")
}
}
If I use the following code they are run simultaneously but in the background thread.
@objc func doWorkFunctions(){
taskGroup.enter()
DispatchQueue.global(qos: .background).async {
self.firstFunction {
self.taskGroup.leave()
}
}
taskGroup.enter()
DispatchQueue.global(qos: .background).async {
self.secondFunction {
self.taskGroup.leave()
}
}
taskGroup.notify(queue: .main) {
print("All tasks completed")
}
}
I've been searching and searching but I can't seem to find an answer to my problem or clarity for that matter. Can someone provide some guidance as to what's going on here. These are the functions in question in case. They simulate a long task to practice tracking progress.
func firstFunction(completion: @escaping()->Void){
print(Thread.current)
if childProgressOne.isCancelled { return }
for i in 1...5 {
sleep(1)
childProgressOne.completedUnitCount = Int64(i * 20)
print("Child Progress One: \(childProgressOne.fractionCompleted)")
print("Total Progress: \(totalProgress.fractionCompleted)")
}
completion()
}
func secondFunction(completion: @escaping()->Void){
print(Thread.current)
if childProgressTwo.isCancelled { return }
for i in 1...5 {
sleep(1)
childProgressTwo.completedUnitCount = Int64(i * 20)
print("Child Progress Two: \(childProgressTwo.fractionCompleted)")
print("Total Progress: \(totalProgress.fractionCompleted)")
}
completion()
}
This also performs them in order but calling Thread.current inside the functions tells me they are being performed in the Main thread even though they are being called to a background thread.
@objc func doWorkFunctions(){
DispatchQueue.global(qos: .background).sync {
self.taskGroup.enter()
self.firstFunction {
self.taskGroup.leave()
}
self.taskGroup.enter()
self.secondFunction {
self.taskGroup.leave()
}
}
taskGroup.notify(queue: .main) {
print("All tasks completed")
}
}