我将 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 的异步调用,它会显示正常。
我怀疑 WPF 期望StartupUri
要设置before OnStartup
返回。所以,我会尝试在中显式创建窗口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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)