Reputation: 3677
I have write a class to handle DispatchQueues
. I have write a static method to invoke main
thread. I pass a completionHandler
as an argument and current just accessing the main thread and call this completion handler inside the main thread block. This cause hanging when this method is called several time concurrently so I want to check if method is already invoked by a main thread then I shouldn't dispatch a queue rather than I just call the completion handler but when I call this completionHandler
it goes into some other thread but not as main thread.
Here is my class
class ETQueue: NSObject {
static func main(completion: @escaping()->()) {
if Thread.isMainThread {
// If current thread is main the i am calling the completion handler but execution of this completionHandler
//Takes the thread to some other level.
completion()
}else {
DispatchQueue.main.sync {
completion()
}
}
}
static func main(_ deley: Double, completion: @escaping()->()) {
DispatchQueue.main.asyncAfter(deadline: .now() + deley) {
completion()
}
}
static func background(completion: @escaping()->()) {
DispatchQueue.global(qos: .background).async {
completion()
}
}
}
Upvotes: 2
Views: 217
Reputation: 1714
There is an alternate way for what you want to achieve. For this first, you need to send it on a background thread and then dispatch again on the main thread.
class ETQueue: NSObject {
static func main(completion: @escaping()->()) {
ETQueue.background {
DispatchQueue.main.sync {
completion()
}
}
}
static func main(_ deley: Double, completion: @escaping()->()) {
ETQueue.background {
DispatchQueue.main.asyncAfter(deadline: .now() + deley) {
completion()
}
}
}
static func background(completion: @escaping()->()) {
DispatchQueue.global(qos: .background).async {
completion()
}
}
}
Upvotes: 1