简体   繁体   中英

Dispatch Queues - Nesting, Optimisation & Control

Can I have your advice on the approved approach?

I have four processes that need to run sequentially:

calculateProcess1()
calculateProcess2()
calculateProcess3()
calculateProcess4()

These calculate data and update progress bars (circular) and other screen literals using dispatch queues to make the UI update.

Run them as is and lo and behold they all fire off simultaneously (what a surprise!).

How do I make the top level calls run in sequence (as above) and do I need to make changes to my DispatchQueues in the processes for updating the literals, eg:

DispatchQueue.main.sync { 
     let progressPercentage = (day*100/365)
     self.progressLabel.text = String(Int(progressPercentage))+"%"  
}

The initiating processes (calculateProcess1-4()) need to run from main. Should this be in ViewDidLoad, a button action or what is the most secure method?

1- Don't sync in main thread as it'll cause a runtime crash , it should be async

DispatchQueue.main.sync { 

2-

Should this be in ViewDidLoad, a button action or what is the most secure method?

it's up to you there is no thing related to security here , implement it as your UX

3- to run them in dequence create a custom Queue then dispatch them in it as it' ll run serially if the code inside all these methods run in the same thread of the queue meaning you don't internally dispatch inside another queue , you can also use DispatchGroup to be notified when all are done

A one approach would be to use Operation and OperationQueue . Setting maxConcurrentOperationCount: Int to 1 on the OperationQueue , will force operations to be performed in a sequence, one after another.

(Previously called NSOperation and NSOperationQueue )

This blogpost can be helpful: https://nshipster.com/nsoperation/

And of course awesome WWDC15 session: Advanced NSOperations

If you want to keep it simple you can provide callback blocks to your calculateProcess methods and simply nest them.

calculateProcess1() {
    calculateProcess2() {
        calculateProcess3() {
            calculateProcess4() {}
        }
    }
}

Should this be in ViewDidLoad, a button action or what is the most secure method?

viewDidLoad is probably what you want. Keep in mind if you instantiate a new viewController of the same type and show it, it will happen again, once, for that new controller as well. Also, if you are doing anything with view frames, those are not guaranteed to be laid out in viewDidLoad , but if you are simply updating text then it should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM