How to ensure to run some code on same background thread?

后端 未结 2 486
时光说笑
时光说笑 2020-12-10 07:13

I am using realm in my iOS Swift project. Search involve complex filters for a big data set. So I am fetching records on background thread.

But realm can be used onl

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 07:30

    You have to create your own thread with a run loop for that. Apple gives an example for a custom run loop in Objective C. You may create a thread class in Swift with that like:

    class MyThread: Thread {
        public var runloop: RunLoop?
        public var done = false
    
        override func main() {
            runloop = RunLoop.current
            done = false
            repeat {
                let result = CFRunLoopRunInMode(.defaultMode, 10, true)
                if result == .stopped  {
                    done = true
                }
            }
            while !done
        }
    
        func stop() {
            if let rl = runloop?.getCFRunLoop() {
                CFRunLoopStop(rl)
                runloop = nil
                done = true
            }
        }
    }
    

    Now you can use it like this:

        let thread = MyThread()
    
        thread.start()
        sleep(1)
        thread.runloop?.perform {
            print("task")
        }
        thread.runloop?.perform {
            print("task 2")
        }
        thread.runloop?.perform {
            print("task 3")
        }
    

    Note: The sleep is not very elegant but needed, since the thread needs some time for its startup. It should be better to check if the property runloop is set, and perform the block later if necessary. My code (esp. runloop) is probably not safe for race conditions, and it's only for demonstration. ;-)

提交回复
热议问题