BLE. MBS WinBluetoothLE memory leak

Using Windows 10 and Windows 11 I noticed that we have a memory leak when adding and delete a BLE device. To make things simpler, I used an example from the MBS xojo plugins set (BluetoothLE Device). This example find a BLE device by required name and then find and fill the device with one custam service and characteristics of this service. I only added 2 buttons: to add new device and delete all devices. Devices are contained in the Devices() of the MainWindow.

I noticed, when I delete a device, it’s still contained in memory(1 WindowsBluetoothLEDevice, 1 WindowsGattDeviceService, 2 WindowsGattCharacteristic in our case). When I add a new one this set of objects is increased by one.

Code of delete button:

for each device as WindowsBluetoothLEDevice in Self.Devices
  
  for each service as WindowsGattDeviceService in device.GattServices
    
    for each characteristic as WindowsGattCharacteristic in service.Characteristics
      
      characteristic.Destructor
      
    next
    
    service.Session.Close
    
    service.Characteristics.RemoveAll
    service.Close
    
  next
  
  device.GattServices.RemoveAll
  device.Pairing.Close
  device.Close
  
next

Devices.RemoveAll

I tried to use everything available for destruction, but nothing helps. Maybe I missed something?

Interesting details: BLE device is removed from memory if you do not use GetGattServicesAsync and RequestAccessAsync. The same thing for services - they leave memory if you don’t call GetCharacteristicsAsync or any.

I can check this. Maybe we reference an object for the async operation and don’t clean it again.

you should never call “Destructor” method yourself. This happens automatically. Also if you make a subclass, you can add a destructor method to log when the object gets destroyed.

By calling service.Characteristics you ask the plugin to create the WindowsGattCharacteristicMBS objects which you then destroy.

It would be great if you could check this, please.
I know about “Destructor”, but thanks for reminding. I used it out of desperation…

Thanks for reporting. I found two missing calls to release:

  • Fixed a memory leak in the RequestAccessCompleted event of WindowsBluetoothLEDeviceMBS class.
  • Fixed a memory leak in the RequestAccessAsyncCompleted event of WindowsGattDeviceServiceMBS class.
2 Likes

Good news!
Question off topic: Do you remember we have a pairing problem on Windows 10?
I found a solution to call method DeviceInformation.Pairing.Custom.PairAsync in background instead of DeviceInformation.Pairing.PairAsync. From this topic: c# - DeviceInformation PairAsync not working in WPF - Stack Overflow

I made a c# .dll to call this method natively from Xojo. If it’s not too much trouble, could you extend MBS WinBluetoothLE with this method in one of the next releases?