2013-01-06 78 views
12

一切都在今天工作,直到它停止...下面是最低的源代碼(我正在使用VS 2012更新1,。淨4.5)。當我運行它時,app在退出時調用client.PostAsync(),所以它永遠不會到達Console.ReadLine()。同樣在調試器,沒有例外,沒有什麼,退出代碼0.HttpClient.PostAsync敲出應用程序退出代碼0

我試過重新啓動機器,重新啓動VS2012 - 沒有任何工作。

再次,一切都在今天運行,不知道什麼改變(沒有軟件已安裝等,所有其他網絡應用程序仍然工作)。

任何想法?我想我正在放鬆自己的想法。

class Program 
{ 
    static void Main(string[] args) 
    { 
     Run(); 
    } 

    private async static void Run() 
    { 
     using (var client = new System.Net.Http.HttpClient()) 
     { 
      var headers = new List<KeyValuePair<string, string>> 
           { 
            new KeyValuePair<string, string>("submit.x", "48"), 
            new KeyValuePair<string, string>("submit.y", "15"), 
            new KeyValuePair<string, string>("submit", "login") 
           }; 

      var content = new FormUrlEncodedContent(headers); 

      HttpResponseMessage response = await client.PostAsync("http://www.google.com/", content); 

      Console.ReadLine(); 
     } 
    } 
} 

回答

29

你的問題是,當其Main()方法完成一個程序正常退出。並且您的Main()只要在Run()中點擊await就完成,因爲這是async方法的工作方式。

你應該做的是讓Run()async Task方法,然後等待TaskMain()方法:

static void Main() 
{ 
    RunAsync().Wait(); 
} 

private static async Task RunAsync() 
{ 
    … 
} 

很少有更多音符:

  1. 你不應該使用async void方法,除非你必須(這是異步事件處理程序的情況)。
  2. 在GUI應用程序或ASP.NET中混合使用awaitWait()是很危險的,因爲它會導致死鎖。但是如果您想在控制檯應用程序中使用async,則這是正確的解決方案。
+5

+1。作爲一個提示,在'RunAsync'而不是'Main'中執行頂級'try' /'catch'會更容易,因爲Task.Wait'會將異常包裝到'AggregateException'中。 –