Dear Yang:
Found the solution to the problem.
Somehow serialDevice
is still held somewhere by the SerialDevice serialDevice = await SerialDevice.FromIdAsync(serialDeviceInfo.Id);
instruction and once detected it does not detect it again and indicates null at if (serialDevice != null)
so once detected it never detects it again even though the foreach goes through each element in the Device collection where the ports ARE accounted for.
The solution is that after the detection as not null (the first time it detects it) of the COM port I have added a serialDevice.Dispose()
which frees this serialDevice for later detection on another click of the update button. The issue changing from one app in the task bar to another doesn't trigger the function anymore. Maybe some kind of bug or unexpected behaviour but the serialDevice.Dispose() got rid of this issue also.
All works now.
Your help has been very much appreciated. Thank you.
The code of the async function is as follows:
private async void ActualizarPuertosSerie()
{
serialDeviceInfos = await DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector());
PuertosSerieDisponibles.Clear();
PuertosSerieDisponibles.Add("NO COM");
foreach (DeviceInformation serialDeviceInfo in serialDeviceInfos)
{
try
{
SerialDevice serialDevice = await SerialDevice.FromIdAsync(serialDeviceInfo.Id);
if (serialDevice != null)
{
PuertosSerieDisponibles.Add(serialDevice.PortName);
serialDevice.Dispose();
} else
{
// Nothing for now
}
}
catch (Exception)
{
// Error. Nothing for now
}
}
}