Exception thrown when calling async task on Winui C#

Paul Harvey Chiverton Messina 5 Reputation points
2024-03-21T18:06:44.23+00:00

Dear everybody.

Using Microsoft Visual Studio Community 2022 (64 bits) - Current Versión 17.9.3 on Windows 10 most recent update, Packaged WinUI with C#

I am programming from scratch a new program (WinUI with C#) to manage my motorized telescope and I am trying to communicate with my 32 but microcontrollers. I have succeded in listing all available serial ports. On startup I call the function that reads all available ports waiting on the task as I need the list of ports in order to select the last port I used (saved in a file) and select it on a combobox of available ports from the start. All goes well. ComboBox works, etc. I select a different port and close the program and this selected port is saved on my configuration file for next opening of the program.

The problem arises when in the program I click a button to update the list of serial ports just in case there is a new available port. This button calls a function Private void ActualizarPS(object sender, RoutedEventArgs e) which calls Task.Run(async () => { await ActualizarPuertosSerie(); }).Wait(); (the same way as at startup) but I get an exception thrown (at the end below) at this call.

Why? Any solution?

CODING

=============

public MainProgram()

{

this.InitializeComponent();

FUNCIONES.InicializarVariables(); // Inicialización variables GLOBALES del programa

Task.Run(async () => { await archivoConfiguracion(false); }).Wait(); // Leer archivo de configuración

Task.Run(async () => { await ActualizarPuertosSerie(); }).Wait(); // Actualizar / leer puertos serie disponibles

... }

private async Task ActualizarPuertosSerie()

{

if (GLOBALES.CloseProgramOK == false) { // Cierre programa no invocado

if (GLOBALES.AbiertoPuertoSerie == false)

{ // Puerto serie no está abierto

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();

}

}

catch (Exception)

{

// Error. Nothing for now

}

}

}

else

{

MostrarMensajes("PUERTO SERIE AÚN ABIERTO", "Debe cerrar el puerto serie\nantes de actualizar la lista.", 1);

}

}

}

// Rutina que actualiza los puertos serie disponibles en el selector combo

private void ActualizarPS(object sender, RoutedEventArgs e)

{

if (GLOBALES.AbiertoPuertoSerie == false) // Puerto serie no está abierto

{

Task.Run(async () => { await ActualizarPuertosSerie(); }).Wait(); // Actualizar / leer puertos serie disponibles

}

else

{

MostrarMensajes("PUERTO SERIE AÚN ABIERTO", "Debe cerrar el puerto serie\nantes de actualizar la lista.", 1);

}

}

EXCEPTION THROWN

==================================

System.AggregateException

HResult=0x80131500

Mensaje = One or more errors occurred. ()

Origen = System.Private.CoreLib

Seguimiento de la pila:

en System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)

en System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)

en System.Threading.Tasks.Task.Wait()

en StellaeTempus.MainProgram.ActualizarPS(Object sender, RoutedEventArgs e) en X:\OneDrive\Programación\StellaeTempus\StellaeTempus\StellaeTempus\MainProgram.xaml.cs: línea 326

en ABI.Microsoft.UI.Xaml.RoutedEventHandler.Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e)

Esta excepción se generó originalmente en esta pila de llamadas:

[Código externo]

StellaeTempus.MainProgram.ActualizarPuertosSerie() en MainProgram.xaml.cs

StellaeTempus.MainProgram.ActualizarPS.AnonymousMethod__16_0() en MainProgram.xaml.cs

Excepción interna 1:

COMException:

Any help appreciated.

Best Regards

Paul Harvey Chiverton

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,218 questions
Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
798 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.
11,039 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.