2017-04-05 62 views
1

因此,我構建了一個小程序來使用REST api,但它永遠不會結束,因爲沒有收到任何數據。我是新來的使用異步和等待命令,所以我可能以某種方式錯誤地得到它。負責檢索數據的線程在幾秒鐘後就超時了。該網址本身是有效的,但似乎沒有異常拋出。在使用休息時發生死鎖API

using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.Linq; 
using System.Net.Http; 
using System.Net.Http.Headers; 
using System.Text; 
using System.Threading.Tasks; 

namespace Bot_Application1 
{ 
    [Serializable] 
    public class ConsumeFOAAS 
    { 
     private static HttpClient client = new HttpClient(); 
     private static String message = "empty"; 


     public String GetMessage() 
     { 
      RunAsync().Wait(); 
      return message; 
     } 


     static async Task RunAsync() 
     { 
      client.BaseAddress = new Uri("http://foaas.com/"); 
      client.DefaultRequestHeaders.Accept.Clear(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain")); 

      try 
      { 
       message = await GetProductAsync("/because/:Insultinator"); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e.Message); 
      } 
     } 


     static async Task<String> GetProductAsync(string path) 
     { 
      Debug.WriteLine("Inside GetProductAsync"); 
      String product = "empty"; 
      HttpResponseMessage response = await client.GetAsync(path); //<--This never finishes 
      Debug.WriteLine("Response: " + response); 
      if (response.IsSuccessStatusCode) 
      { 
       product = await response.Content.ReadAsStringAsync(); 
      } 
      return product; 
     } 
    } 
} 
+0

'RunAsync()等待();'是一個壞主意。使用'await RunAsync();' –

回答

0

你不應該叫.Wait()。最好等待達到你想要的是:

public async Task<String> GetMessage() 
{ 
    return await RunAsync(); 
} 

並更改RunAsync功能:

static async Task<string> RunAsync() { 

client.BaseAddress = new Uri("http://foaas.com/"); 
client.DefaultRequestHeaders.Accept.Clear(); 
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain")); 

try { 
    return await GetProductAsync("/because/:Insultinator"); 
} catch (Exception e) { 
    Console.WriteLine(e.Message); 
} 

}