'BluetoothLEDevice.GetGattServicesAsync() throws "Value does not fall within the expected range." exception

I wrote a simple app that monitors BLE advertisements. When the app receives an advertisement it calls BluetoothLEDevice.FromBluetoothAddressAsync() and if that call returns a non null value GetGattServicesAsync() is called (see code below). Occasionally GetGattServicesAsync() will throw a "Value does not fall within the expected range."

private async void WatcherAdvertisementReceivedAsync(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher sender, 
                                                 BluetoothLEAdvertisementReceivedEventArgs args)
{
    using var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

    if (device == null)
        return;

    try
    {
        var gatt = await device.GetGattServicesAsync();
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source