TruMan1 TruMan1 - 4 years ago 72
Swift Question

How to execute block on thread instance?

I perform

URLSession.shared.downloadTask
request, but would like to execute code on the same thread the
downloadTask
was executed on. For example:

func sample() {
let thread = Thread.current

URLSession.shared.downloadTask(with: file) {
someFunc() //How to execute on thread variable?
}.resume()
}


In the
downloadTask
completion handler, it is running on a background thread. However, I'd like to call
someFunc()
on the same thread
sample()
was called on. How do I do something like
Thread.current.async {...}
so I can do this:

func sample() {
let thread = Thread.current

URLSession.shared.downloadTask(with: file) {
thread.async { someFunc() } //Doesn't compile
}.resume()
}

Rob Rob
Answer Source

If you want to run something on a particular Thread, you wouldn't use this GCD API, but rather just:

perform(#selector(someMethod), on: thread, with: nil, waitUntilDone: false, modes: [RunLoopMode.commonModes.rawValue])

That of course assumes that you created a thread with a run loop, e.g.:

let thread = Thread(target: self, selector: #selector(threadEntryPoint), object: nil)
thread.start()

and

func threadEntryPoint() {
    autoreleasepool {
        Thread.current.name = "com.domain.app.background"
        let runLoop = RunLoop.current
        runLoop.add(NSMachPort(), forMode: .defaultRunLoopMode)
        runLoop.run()
    }
}

For more information, see the Threading Programming Guide.

Personally, I'd personally stay within GCD if humanly possible, but you said elsewhere that you have some unique requirement that precludes that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download