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

时间:2015-03-10 15:44:08

标签: c# wpf asp.net-web-api async-await

我将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的异步调用,则显示正常。

2 个答案:

答案 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) =>
   {
     ...
   };

或者你可以选择另一个相关的事件。