使用调试器运行这行代码
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()
答案 0 :(得分:0)
Task.Run(() => translate("en", "bg", "hello")).Wait();
代码正在运行,您需要进行一些小调整以等待在Task.Run
创建的任务