首页 > 解决方案 > 如果提供了无效域,则 HttpClient 或 WebClient 需要很长时间

问题描述

从无法解析的域中获取数据时,进入 catch 块需要超过 10 秒的时间。

try
{
    var resultDomain = client.GetAsync("http://nonexistent.nonexistent.nonexistent").Result.Content.ReadAsStringAsync().Result;
}
catch(Exception ex)
{
    //outputs 
    //The remote name could not be resolved: 'nonexistent.nonexistent.nonexistent'
    //11,0632079
    Console.WriteLine(ex.InnerException.InnerException.Message);
    Console.WriteLine(watch.Elapsed.TotalSeconds);
}

这虽然命令

nslookup nonexistent.nonexistent.nonexistent

几乎立即完成域不存在的通知。有没有办法让 HttpClient/WebClient/... 的行为与 nslookup 一样快?.NET 还在等什么?

根据wireshark的说法,DNS会立即响应

在此处输入图像描述

标签: c#.netperformancedns

解决方案


将超时设置为低于默认值 100 秒怎么样?

client.Timeout = TimeSpan.FromMilliseconds(500);
client.GetAsync(...);

推荐阅读