wpf connect ble device service takes too long time when use task

C.Return 1 Reputation point
2021-10-19T17:47:17.763+00:00

I have A WPF application,it has many pages,this page connect to different ble device (e.g thermometer、sphygmomanometer and so on).Some ble device should light up the screen can find gatt services,if the screen is not turn on,can't get gatt service.When I in this page,but the device screen not on,I go to other page,the app UI will freeze.Here is the code:

 public partial class PageTemp : Page
        {
            public PageTemp()
            {
                InitializeComponent();
            }
            private string _ServiceId { get; set; }
            private string _Uuid { get; set; }
            private async void Page_Loaded(object sender, RoutedEventArgs e)
            {
                var bleDeviceId = ConfigHelper.GetConfig("TempBleDevice");
                if (string.IsNullOrEmpty(bleDeviceId))
                {
                    return;
                }
                _ServiceId = "0000fe18-0000-1000-8000-00805f9b34fb";
                _Uuid = "0000fe10-0000-1000-8000-00805f9b34fb";
                TxtStatus.Text = "Connecting…";
                await Task.Run(() => ConnectServiceAsync(bleDeviceId));
            }
            BluetoothLEDevice deviceLEDevice;
            private GattDeviceService CurrentService;
            private GattCharacteristic CurrentNotifyCharacteristic;
            private bool IsLeave = false;
            private async Task ConnectServiceAsync(string deviceId)
            {
                await Task.Delay(50);
                deviceLEDevice = await BluetoothLEDevice.FromIdAsync(deviceId);
                while (deviceLEDevice == null)
                {
                    deviceLEDevice = await BluetoothLEDevice.FromIdAsync(deviceId);
                    await Task.Delay(50);
                }
                if (!deviceLEDevice.DeviceInformation.Pairing.CanPair)
                {
                    Dispatcher.Invoke(() =>
                    {
                        TxtStatus.Text = "device can't pair";
                        TxtStatus.Foreground = new SolidColorBrush(Colors.Red);
                    });
                    return;
                }
                deviceLEDevice.ConnectionStatusChanged += BluetoothLEDevice_ConnectionStatusChanged;
                var serviceId = Guid.Parse(_ServiceId);
                var services = await deviceLEDevice.GetGattServicesForUuidAsync(serviceId);//here takes too long time
                if (services.Status != GattCommunicationStatus.Success)
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        TxtStatus.Text = "service unreachable";
                        TxtStatus.Foreground = new SolidColorBrush(Colors.Red);
                    }));
                    return;
                }
                foreach (var service in services.Services)
                {
                    var characteristicsResult = await service.GetCharacteristicsAsync();
                    Console.WriteLine("characteristicsResult.Status:" + characteristicsResult.Status);
                    if (characteristicsResult.Status == GattCommunicationStatus.Success)
                    {
                        var characteristics = characteristicsResult.Characteristics;
                        foreach (var characteristic in characteristics)
                        {
                            if (characteristic.Uuid.ToString().ToLower() == _Uuid)
                            {
                                CurrentService = service;
                                Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
                                if (properties.HasFlag(GattCharacteristicProperties.Notify))
                                {
                                    GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                                    if (status == GattCommunicationStatus.Success)
                                    {
                                        CurrentNotifyCharacteristic = characteristic;
                                        CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;
                                    }
                                }
                            }
                        }
                    }
                }
            }


            private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
            {
                byte[] data;
                CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out data);
                string str = BitConverter.ToString(data);
                Console.WriteLine("data changed:" + str + "\r\n");
            }

            private void BluetoothLEDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)
            {
                Console.WriteLine("ConnectionStatusChanged:" + sender.ConnectionStatus);
                if (sender != null)
                {
                    if (sender.ConnectionStatus == BluetoothConnectionStatus.Connected)
                    {
                        Dispatcher.Invoke(new Action(() =>
                        {
                            TxtStatus.Text = "connected";
                            TxtStatus.Foreground = new SolidColorBrush(Colors.LightGreen);
                        }));
                    }
                    else
                    {
                        Dispatcher.Invoke(new Action(() =>
                        {
                            TxtStatus.Text = "disconnected";
                            TxtStatus.Foreground = new SolidColorBrush(Colors.Orange);
                            if (CurrentNotifyCharacteristic != null)
                            {
                                CurrentNotifyCharacteristic.ValueChanged -= Characteristic_ValueChanged;
                            }
                            var bleDeviceId = ConfigHelper.GetConfig("TempBleDevice");
                            Task.Run(() =>
                            {
                                ConnectServiceAsync(bleDeviceId);
                            });
                        }));
                    }
                }
            }


            private void Page_Unloaded(object sender, RoutedEventArgs e)
            {
                try
                {
                    if (deviceLEDevice != null)
                    {
                        IsLeave = true;
                        CurrentService?.Dispose();
                        deviceLEDevice?.Dispose();
                        deviceLEDevice = null;
                        CurrentNotifyCharacteristic = null;
                        Console.WriteLine("device disconnected");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("device disconnected error:" + ex.Message);
                }
            }
        }

var services = await deviceLEDevice.GetGattServicesForUuidAsync(serviceId); This makes too long time. when I go to other page the UI freeze if ble device screen turn off.What should I do?

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,671 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,249 questions
0 comments No comments
{count} votes