gpt4 book ai didi

c# - 从 App.OnStartup 调用异步 Web API 方法

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:11 25 4
gpt4 key购买 nike

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

关于c# - 从 App.OnStartup 调用异步 Web API 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28968015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com