Poulpynator
Poulpynator

Reputation: 1176

Win32 exception then using Httpclient inside Application constructor

I am trying to load some files in my .NET MAUI application, I am using HttpClient inside my Application constructor (I know that I should be using App lifecycle events) :

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
        TestAsync();
    }

    private async Task TestAsync()
    {
        HttpClient lClient = new HttpClient();
        var lReponse = await lClient.GetAsync(new Uri("https://proof.ovh.net/files/1Mb.dat"));
        using (var fs = new FileStream(@"C:\test.dat", FileMode.CreateNew))
        {
            await lReponse.Content.CopyToAsync(fs);
        }
    }
}

I always end up with the following error on Windows (An unhandled win32 exception occurred) on the var lReponse = await lClient.GetAsync part :

enter image description here

In a .NET 6 WPF project this is working fine :

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        TestAsync();
    }

    private async Task TestAsync()
    {
        HttpClient lClient = new HttpClient();
        var lReponse = await lClient.GetAsync(new Uri("https://proof.ovh.net/files/1Mb.dat"));
        using (var fs = new FileStream(@"C:\test.dat", FileMode.CreateNew))
        {
            await lReponse.Content.CopyToAsync(fs);
        }
    }
}

Is there something specific in the lifecycle of the Application class that impact async/await (something related to the SynchronizationContext ?) ?

Thanks for your help !

Upvotes: 0

Views: 209

Answers (1)

Poulpynator
Poulpynator

Reputation: 1176

The error was caused by the missing MainPage initalization. In .NET MAUI you have to set MainPage in the constructor of App, this will fix my code sample :

public App()
{
   InitializeComponent();
   TestAsync();

   MainPage = new AppShell();
}

I found out thanks to this stackoverflow, how you can handle this type of unhandled exception like so :

public App()
{
    // Catch all handled exceptions in managed code, before the runtime searches the Call Stack 
    AppDomain.CurrentDomain.FirstChanceException += FirstChanceException;
    InitializeComponent();
    TestAsync();
}

private void FirstChanceException(object sender, FirstChanceExceptionEventArgs e)
{
    Console.WriteLine(e.ToString());
}

Which gave me the following exception :

System.NotImplementedException: 'Either set MainPage or override CreateWindow.'

In my original code I was setting the main page after the await of my async call, which is after the constructor finished it's execution hence the error (no idea it was hide by a win32 unhandled exception though).

Upvotes: 2

Related Questions