因此,我構建了一個小程序來使用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;
}
}
}
'RunAsync()等待();'是一個壞主意。使用'await RunAsync();' –