从 App.OnStartup 调用异步 Web API 方法

Calling async Web API method from App.OnStartup

我将 App.OnStartup 更改为异步,以便我可以在网络上调用异步方法 api,但现在我的应用程序不显示其 window。我在这里做错了什么:

    protected override async void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        HttpResponseMessage response = await TestWebAPI();
        if (!response.IsSuccessStatusCode)
        {
            MessageBox.Show("The service is currently unavailable"); 
            Shutdown(1);
        }

        this.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
    }

    private async Task<HttpResponseMessage> TestWebAPI()
    {
        using (var webClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
        {
            webClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["WebApiAddress"]);
            HttpResponseMessage response = await webClient.GetAsync("api/hello", HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);
            return response;
        }
    }
}

如果我去掉对 TestWebAPI 的异步调用,它显示正常。

你试过了吗?

this.OnStartup += async (s, e) =>
   {
     ...
   };

this.Loaded += async (s, e) =>
   {
     ...
   };

或者您可以选择另一个相关的事件。

我怀疑 WPF 希望 StartupUri 之前 OnStartup returns 被设置。所以,我会尝试在 Startup 事件中明确创建 window:

private async void Application_Startup(object sender, StartupEventArgs e)
{
  HttpResponseMessage response = await TestWebAPIAsync();
  if (!response.IsSuccessStatusCode)
  {
    MessageBox.Show("The service is currently unavailable"); 
    Shutdown(1);
  }
  MainWindow main = new MainWindow();
  main.DataContext = ...
  main.Show();
}