我有以下代码;
var httpClientHandler = new HttpClientHandler()
{
UseDefaultCredentials = true,
PreAuthenticate = false,
};
var webclient = new HttpClient(httpClientHandler);
webclient.BaseAddress = new Uri("http://localhost");
webclient.Timeout = new TimeSpan(1);
var res = webclient.PostAsync("http://localhost/test", "'test'", new JsonMediaTypeFormatter()).Result; //.ContinueWith(x => ProcessResult(x));
.Result阻塞线程并挂起应用程序。如果我用延续替换它,它永远不会被执行。
如果我增加超时,代码就会起作用,所以似乎是失败的超时。
我已经通过使用另一个任务来解决它,但想要更好地理解;
if (await Task.WhenAny(task, Task.Delay(new TimeSpan(0, 0, 0, 20))) == task)
{
//success
}
else
{
//failure
}