emqx / CocoaMQTT

MQTT 5.0 client library for iOS and macOS written in Swift
https://www.emqx.com/en
Other
1.6k stars 419 forks source link

Why is delegateQueue run on main thread? #498

Open developer-bk opened 1 year ago

developer-bk commented 1 year ago

Hi!! I have a issue about application performance when using CocoaMQTT5. My app receives message once every second (maybe less time). Even if i don't process anything when i receive the message, when i scroll tableview, my tableview lags I have checked source code and i see delegateQueue is running on main thread. Maybe that's why My UI is stuck on some where. i have re-set backgroundOnSocket running in background thread. So, what's the problem if i put backgroundOnSocket running on background thread ? (Of course I will put UI update tasks on the main thread)

CocoaMQTT5 default: image

I set: image

Thank you so much

leeway1208 commented 1 year ago

Here are some docs https://developer.apple.com/documentation/foundation/nsthread?language=objc

Choice-Fei commented 1 year ago

I also have this problem,when receives many message every second ,My UI is stuck.

EInfochips-Priyank commented 3 months ago

I have same problem, when receives many message every second ,My UI is stuck. @Choice-Fei @developer-bk Did you find any solution?

developer-bk commented 3 months ago

@EInfochips-Priyank @Choice-Fei You guys can try to use a custom DispatchQueue:

let mqttDispatch = DispatchQueue(label: "mqttDelegate", qos: .userInteractive) configuration: mqtt = CocoaMQTT5(clientID: clientID, host: host, port: port) mqtt?.delegateQueue = mqttDispatch This will help the MQTT process run in the background, on only the queue. The function didReceiveMessage also runs on this queue(background). if you update the UI on this function, that will make the errors. You have to make sure when you update the UI, you have to update UI in the main thread.

developer-bk commented 3 months ago

I set the delegateQueue like the image in the first post and got random crashes. Because the process in the MQTT library is not optimized for multithreading. If you process them using multi-thread, at some point, your app will crash due to reading and writing data to a variable at the same time. So I think you guys should use a serial queue for this process

developer-bk commented 3 months ago

@EInfochips-Priyank Please use it and let me know the results. I don't have enough results yet to be able to conclude whether it is good enough or not