从调用异步App.OnStartup网络API方法(Calling async Web API me

2019-10-22 05:36发布

我改变App.OnStartup是异步,这样我可以调用一个Web API异步方法,但现在我的应用程序不会显示其窗口。 我在做什么错在这里:

    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它显示的罚款。

Answer 1:

我怀疑WPF预计StartupUri之前设置OnStartup回报。 所以,我想尝试在明确创建窗口Startup事件:

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


Answer 2:

你试试这个?

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

要么

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

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



文章来源: Calling async Web API method from App.OnStartup