[英]Swift: Choose queue for Bluetooth Central manager
I'm working on the app that will connect with a smart device via BLE and communicate with it. 我正在研究通过BLE与智能设备连接并与之通信的应用程序。
The question is: In what queue is the best practice to handle bluetooth events? 问题是: 处理蓝牙事件的最佳做法是什么队列?
I've read a lot of tutorials and in all of them I found this: 我已经阅读了很多教程,在所有这些教程中我发现了这个:
centralManager = CBCentralManager(delegate: self, queue: nil)
They choose to handle bluetooth events in main queue ( queue: nil
), but I suppose that it's not good practice. 他们选择在主队列中处理蓝牙事件(
queue: nil
),但我认为这不是好习惯。 Because it could be a lot of queries send to peripheral device from central and a lot of answers send from peripheral to central. 因为它可能是很多查询从中心发送到外围设备而且很多答案都是从外设发送到中心的。
I assume this might be the reason of the app working slowly and might detrimentally affect the productivity, am I right? 我认为这可能是应用程序工作缓慢的原因,可能会对生产力产生不利影响,对吗?
Will this flood the UI update queue? 这会淹没UI更新队列吗?
I am using dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) for the CBCentralManager for some time in my Bluetooth projects and it is working flawlessly. 我在我的蓝牙项目中使用了dispatch_get_global_queue(QOS_CLASS_BACKGROUND,0)作为CBCentralManager已经有一段时间了,它正在完美运行。
^ Scratch that. ^抓挠那个。 I wouldn't recommend using the global queue.
我不建议使用全局队列。 The reason is that the global queue is a concurrent one and you probably want a serial one.
原因是全局队列是并发的,您可能需要一个序列号。 Create a new
DispatchQueue(label: "CentralManager")
and pass it to the CBCentralManager
. 创建一个新的
DispatchQueue(label: "CentralManager")
并将其传递给CBCentralManager
。
All the delegate methods will be delivered to the queue you specify. 所有委托方法都将传递到您指定的队列。 If you do some very light operations on these methods, I guess you could keep the main queue.
如果你对这些方法做了一些非常轻松的操作,我猜你可以保留主队列。 But it is better to use a background queue.
但最好使用后台队列。
You should definitely use a seperate queue for the CBCentralManager
and preferrably also use it for all the communication with the CBPeripheral
object - so your main queue is not getting blocked. 您绝对应该为
CBCentralManager
使用单独的队列,并且最好还将它用于与CBPeripheral
对象的所有通信 - 因此您的主队列不会被阻止。
dispatch_async
the events to your queue should not be a problem - as long as read/write requests are not getting delayed. dispatch_async
将事件发送到您的队列应该不是问题 - 只要读/写请求没有延迟。
From Bluetooth perspective, I don't think queue the events is a best practice; 从蓝牙的角度来看,我认为排队事件不是最佳做法; except you want to delay the sending messages.
除了你想延迟发送消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.