Reputation: 2687
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.
Upvotes: 2
Views: 3474
Reputation: 456322
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();
}
Upvotes: 5
Reputation: 11595
Did you try this?
this.OnStartup += async (s, e) =>
{
...
};
Or
this.Loaded += async (s, e) =>
{
...
};
Or you can pick another event that's related.
Upvotes: -1