private async void DeviceWatcher_Updated()

in BluetoothLEExplorer/BluetoothLEExplorer/Models/GattSampleContext.cs [644:710]


        private async void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
        {
            DeviceInformation di = null;
            bool addNewDI = false;

            try
            {
                // Protect against race condition if the task runs after the app stopped the deviceWatcher.
                if (sender == deviceWatcher)
                {
                    ObservableBluetoothLEDevice dev;

                    // Need to lock as another DeviceWatcher might be modifying BluetoothLEDevices 
                    try
                    {
                        await BluetoothLEDevicesLock.WaitAsync();
                        dev = BluetoothLEDevices.FirstOrDefault(device => device.DeviceInfo.Id == deviceInfoUpdate.Id);
                        if (dev != null)
                        {   // Found a device in the list, updating it
                            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                                Windows.UI.Core.CoreDispatcherPriority.Normal,
                                async () =>
                                {
                                    dev.Update(deviceInfoUpdate);
                                });
                        }
                        else
                        {
                            // Need to add this device. Can't do that here as we have the lock
                            addNewDI = true;
                        }
                    }
                    finally
                    {
                        BluetoothLEDevicesLock.Release();
                    }

                    if(addNewDI == true)
                    {
                        try
                        {
                            await BluetoothLEDevicesLock.WaitAsync();
                            di = unusedDevices.FirstOrDefault(device => device.Id == deviceInfoUpdate.Id);
                            if (di != null)
                            {   // We found this device before.
                                unusedDevices.Remove(di);
                                di.Update(deviceInfoUpdate);
                            }
                        }
                        finally
                        {
                            BluetoothLEDevicesLock.Release();
                        }

                        if (di != null)
                        {
                            await AddDeviceToList(di);
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("DeviceWatcher_Updated: " + ex.Message);
            }
        }