所以我构建了一个小程序来使用REST api,但它永远不会完成,因为没有收到任何数据。我是使用Async和wait命令的新手,所以我可能以某种方式弄错了。负责检索数据的线程在几秒钟后就会超时。网址本身虽然有效,但似乎没有例外。
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 :(得分: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);
}
}
答案 1 :(得分:-1)
死锁可能由任务管理器引起。尝试使用:
RunAsync().ConfigureAwait(false).Wait();
说明:http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html