[英]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. 我将App.OnStartup更改为异步,以便我可以在web api上调用异步方法,但现在我的应用程序没有显示其窗口。 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. 如果我取消对TestWebAPI的异步调用,它显示正常。
I suspect that WPF expects StartupUri
to be set before OnStartup
returns. 我怀疑WPF希望在 OnStartup
返回之前设置StartupUri
。 So, I'd try creating the window explicitly in the Startup
event: 所以,我尝试在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();
}
Did you try this? 你试过这个吗?
this.OnStartup += async (s, e) =>
{
...
};
Or 要么
this.Loaded += async (s, e) =>
{
...
};
Or you can pick another event that's related. 或者你可以选择另一个相关的事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.