C#开发的BLE蓝牙护肤设备配对后无法正常断开连接如何解决
BLE设备无法断开连接修复方案
问题根源
- 仅调用
BluetoothLEDevice.Dispose()只会释放应用层的对象资源,不会主动触发Windows底层和BLE设备的物理连接断开 - 代码中获取的Gatt服务、特征对象都还持有对设备的引用,未完全释放也会导致连接被持有
- 如果设备和Windows做了系统级配对,单纯释放应用内对象不会解除系统层面的连接绑定
- 你提供的断开方法名存在语法问题:
btnDisconnect _Click中间多了空格,大概率没有和按钮的点击事件正确绑定,这也是点击无反应的常见原因
修复步骤
1. 修正断开方法名,完善资源释放逻辑
将断开按钮的代码替换为以下实现:
private async void btnDisconnect_Click(object sender, EventArgs e) { try { // 释放所有Gatt服务资源 if (result != null && result.Services != null) { foreach (var service in result.Services) { service.Dispose(); } } // 释放蓝牙设备核心对象 if (bluetoothLeDevice != null) { bluetoothLeDevice.Dispose(); bluetoothLeDevice = null; } // 置空所有相关引用 result = null; device = null; // 可选:如果需要解除系统级配对,开启下方代码 // if (device != null && device.Pairing.IsPaired) // { // await device.Pairing.UnpairAsync(); // } // 停止设备监听器,移除事件绑定 if (deviceWatcher != null) { deviceWatcher.Stop(); deviceWatcher.Added -= DeviceWatcher_Added; deviceWatcher.Updated -= DeviceWatcher_Updated; deviceWatcher.Removed -= DeviceWatcher_Removed; deviceWatcher.EnumerationCompleted -= DeviceWatcher_EnumerationCompleted; deviceWatcher.Stopped -= DeviceWatcher_Stopped; deviceWatcher = null; } statusBox.Text = "设备已断开连接"; feedbackTB.AppendText("设备已断开" + Environment.NewLine); } catch (Exception err) { ErrorWindow eWindow = new ErrorWindow(); eWindow.label4.Text = err.GetType().ToString(); eWindow.errorDetails.Text = err.Message; eWindow.ShowDialog(); } }
2. 重新绑定事件
到按钮的属性面板中,确认点击事件已经绑定到修正后的btnDisconnect_Click方法。
内容的提问来源于stack exchange,提问作者Jungle Zee
相关产品推荐
相关产品推荐

