简体   繁体   中英

Calling async Web API method from App.OnStartup

I changed App.OnStartup to be async so that I can call an async method on a web api, but now my app does not show its window. What am I doing wrong here:

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

If I take out the async call to TestWebAPI it shows fine.

I suspect that WPF expects StartupUri to be set before OnStartup returns. So, I'd try creating the window explicitly in the Startup event:

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

Did you try this?

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

Or

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

Or you can pick another event that's related.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM