【问题标题】:Win32 exception then using Httpclient inside Application constructorWin32 异常然后在应用程序构造函数中使用 Httpclient
【发布时间】:2023-01-12 21:29:24
【问题描述】:

我试图在我的 .NET MAUI 应用程序中加载一些文件,我在我的 Application 构造函数中使用 HttpClient(我知道我应该使用 App 生命周期事件):

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

在 Windows 上,var lReponse = await lClient.GetAsync 部分总是出现以下错误(发生未处理的 win32 异常):

在 .NET 6 WPF 项目中,这工作正常:

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

Application 类的生命周期中是否有影响异步/等待的特定内容(与 SynchronizationContext 相关的内容?)?

谢谢你的帮助 !

【问题讨论】:

  • 可能您的用户没有权限写入 C:\ 驱动器的根目录
  • 添加一个 try/catch 并获取异常对象并查看它告诉您的内容
  • @daniel-a-white 我尝试了其他路径 (FileSystem.Current.AppDataDirectory),结果相同。在我看来,这不太可能是文件系统问题,因为错误在lClient.GetAsync 上并且它在 WPF 中有效。
  • @Jason 运气不好(同样的错误,同样的地方,捕获永远不会到达)输出中也没有任何内容
  • 请发布完整的异常详细信息,包括消息和调用堆栈。和代码,如果你能得到它。

标签: c# maui


【解决方案1】:

该错误是由于缺少MainPage 初始化造成的。在 .NET MAUI 中,您必须在 App 的构造函数中设置 MainPage,这将修复我的代码示例:

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

   MainPage = new AppShell();
}

感谢thisstackoverflow,我发现了如何处理此类未处理的异常,如下所示:

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

这给了我以下例外:

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

在我的原始代码中,我在等待我的异步调用之后设置主页,这是在构造函数完成它的执行之后出现错误(虽然不知道它被 win32 未处理的异常隐藏了)。

【讨论】:

    猜你喜欢
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多