[英]HttpClient.PostAsync knocks out the app with exit code 0
今天一切都在工作,直到它停止......下面是最小的源代码(我使用的是 VS 2012 Update 1,.Net 4.5)。 当我运行它时,应用程序在调用 client.PostAsync() 时退出,因此它永远不会到达 Console.ReadLine()。 在调试器中也一样,没有例外,什么都没有,退出代码 0。
我尝试重新启动机器,重新启动 VS2012 - 没有任何效果。
同样,今天一切都在运行,不确定发生了什么变化(没有安装软件等,所有其他网络应用程序仍然有效)。
有任何想法吗? 我想我正在失去理智。
class Program
{
static void Main(string[] args)
{
Run();
}
private async static void Run()
{
using (var client = new System.Net.Http.HttpClient())
{
var headers = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("submit.x", "48"),
new KeyValuePair<string, string>("submit.y", "15"),
new KeyValuePair<string, string>("submit", "login")
};
var content = new FormUrlEncodedContent(headers);
HttpResponseMessage response = await client.PostAsync("http://www.google.com/", content);
Console.ReadLine();
}
}
}
您的问题是程序通常在Main()
方法完成时退出。 一旦您在Run()
点击await
,您的Main()
完成,因为这就是async
方法的工作方式。
您应该做的是将Run()
变成async Task
方法,然后在Main()
方法中等待Task
:
static void Main()
{
RunAsync().Wait();
}
private static async Task RunAsync()
{
…
}
在 C# 7.1+ 中,您应该使用async Main
代替:
static async Task Main()
{
await RunAsync();
}
private static async Task RunAsync()
{
…
}
还有一些注意事项:
async void
方法,除非你必须(这是异步事件处理程序的情况)。await
和Wait()
是危险的,因为它会导致死锁。 但如果您想在控制台应用程序中使用async
,这是正确的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.