我将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的异步调用,则显示正常。
答案 0 :(得分:3)
我怀疑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();
}
答案 1 :(得分:0)
你试过吗?
this.OnStartup += async (s, e) =>
{
...
};
或强>
this.Loaded += async (s, e) =>
{
...
};
或者你可以选择另一个相关的事件。