How to disconnect a BLE device after successful connection

Prajnith Kumar 0 Reputation points
2024-06-13T10:31:14.1533333+00:00

I have successfully connected to BLE device by using BluetoothLEDevice.FromIdAsync(deviceInfo.Id) and bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Cached) API's in unpaired mode over Windows 10 with .NET Framework 4.7.2 but I was unsuccessful in disconnecting from the BLE device even with the dispose code listed below and also clearing the characteristics. How do I correctly close the BLE connection?

            try

            {

                var services = Task.Run(async () => await bluetoothLeDevice.GetGattServicesAsync()).Result;

                foreach (var service in services.Services)

                {

                    service?.Session?.Dispose();

                    service?.Dispose();

                }

            }

            catch (Exception ex)

            {

                Debug.WriteLine(ex.Message);

            }

            bluetoothLeDevice?.Dispose();

            int n = 0;

            while (bluetoothLeDevice.ConnectionStatus != BluetoothConnectionStatus.Disconnected)

            {

                Task.Run(async () => Thread.Sleep(1000)); // Wait for the device to disconnect

                Debug.WriteLine($"Checking Disconnection Status!, Delay Seconds: {n}");

                n++;

            }

            bluetoothLeDevice = null;
```Thanks in Advance!

Prajnith

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,709 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,604 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more