HttpClient无法初始化

时间:2017-03-16 14:25:31

标签: c# httpclient

使用调试器运行这行代码

HttpClient client = new HttpClient()

应用程序突然退出。任何人都有一些想法为什么出现这个?

这是代码:

static void Main(string[] args)
    {
        Task.Run(() => translate("en", "bg", "hello").Wait());
    }

static async Task translate(string sourceLang, string targetLang, string sourceText)
{
    string page = "http://www.transltr.org/api/translate?text=" + 
        sourceText + "&to=" + targetLang + "&from=" + sourceLang;

    try
    {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(page);
        response.EnsureSuccessStatusCode();
        if (response.IsSuccessStatusCode)
        {
            string trans = await response.Content.ReadAsStringAsync();
            Console.WriteLine(trans);
            Console.ReadLine();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}

并在此行之后停止执行

HttpClient client = new HttpClient()

1 个答案:

答案 0 :(得分:0)

Task.Run(() => translate("en", "bg", "hello")).Wait(); 

代码正在运行,您需要进行一些小调整以等待在Task.Run

创建的任务