更新:原因:正如其他人所说,Ping 超时不起作用的最可能原因是 DNS 解析。对 getaddrinfo 的系统调用(Dns.GetHostAddresses 和 Ping 使用的系统调用 - https://docs.microsoft.com/en-us/windows/win32/api/ws2tcpip/nf-ws2tcpip-getaddrinfo、https://docs.microsoft.com/en-us/dotnet/api/system.net.dns.gethostaddresses?view=netcore-3.1 - 与完整框架类似)不接受超时。因此,对以下代码的进一步改进是将 dns 查找与 ping 分开。首先使用类似于以下代码的超时方法进行查找,并且仅 ping IP 而不是主机名,并指定超时。
我过去也遇到过类似的问题,我有一些代码可能有助于解决这个问题。我在这里编辑它,所以它可能没有 100% 正确,而且比你的需要复杂一点。可以试试这样的吗?
锤子:(完整的代码和测试结果也包括在下面)
private static PingReply ForcePingTimeoutWithThreads(string hostname, int timeout)
{
PingReply reply = null;
var a = new Thread(() => reply = normalPing(hostname, timeout));
a.Start();
a.Join(timeout); //or a.Abort() after a timeout, but you have to take care of a ThreadAbortException in that case... brrr I like to think that the ping might go on and be successful in life with .Join :)
return reply;
}
private static PingReply normalPing(string hostname, int timeout)
{
try
{
return new Ping().Send(hostname, timeout);
}
catch //never do this kids, this is just a demo of a concept! Always log exceptions!
{
return null; //or this, in such a low level method 99 cases out of 100, just let the exception bubble up
}
}
这是一个完整的工作示例(Tasks.WhenAny 经过测试并在 4.5.2 版中工作)。我还了解到,Tasks 的优雅对性能的影响比我记得的要大,但是 Thread.Join/Abort 对于大多数生产环境来说太残酷了。
using System;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
//this can easily be async Task<PingReply> or even made generic (original version was), but I wanted to be able to test all versions with the same code
private static PingReply PingOrTimeout(string hostname, int timeOut)
{
PingReply result = null;
var cancellationTokenSource = new CancellationTokenSource();
var timeoutTask = Task.Delay(timeOut, cancellationTokenSource.Token);
var actionTask = Task.Factory.StartNew(() =>
{
result = normalPing(hostname, timeOut);
}, cancellationTokenSource.Token);
Task.WhenAny(actionTask, timeoutTask).ContinueWith(t =>
{
cancellationTokenSource.Cancel();
}).Wait(); //if async, remove the .Wait() and await instead!
return result;
}
private static PingReply normalPing(string hostname, int timeout)
{
try
{
return new Ping().Send(hostname, timeout);
}
catch //never do this kids, this is just a demo of a concept! Always log exceptions!
{
return null; //or this, in such a low level method 99 cases out of 100, just let the exception bubble up
}
}
private static PingReply ForcePingTimeoutWithThreads(string hostname, int timeout)
{
PingReply reply = null;
var a = new Thread(() => reply = normalPing(hostname, timeout));
a.Start();
a.Join(timeout); //or a.Abort() after a timeout... brrr I like to think that the ping might go on and be successful in life with .Join :)
return reply;
}
static byte[] b = new byte[32];
static PingOptions po = new PingOptions(64, true);
static PingReply JimiPing(string hostname, int timeout)
{
try
{
return new Ping().Send(hostname, timeout, b, po);
}
catch //never do this kids, this is just a demo of a concept! Always log exceptions!
{
return null; //or this, in such a low level method 99 cases out of 100, just let the exception bubble up
}
}
static void RunTests(Func<string, int, PingReply> timeOutPinger)
{
var stopWatch = Stopwatch.StartNew();
var expectedFail = timeOutPinger("bogusdjfkhkjh", 200);
Console.WriteLine($"{stopWatch.Elapsed.TotalMilliseconds} false={expectedFail != null}");
stopWatch = Stopwatch.StartNew();
var expectedSuccess = timeOutPinger("127.0.0.1", 200);
Console.WriteLine($"{stopWatch.Elapsed.TotalMilliseconds} true={expectedSuccess != null && expectedSuccess.Status == IPStatus.Success}");
}
static void Main(string[] args)
{
RunTests(normalPing);
RunTests(PingOrTimeout);
RunTests(ForcePingTimeoutWithThreads);
RunTests(JimiPing);
Console.ReadKey(false);
}
}
}
我的一些测试结果:
>Running ping timeout tests timeout = 200. method=normal
>
> - host: bogusdjfkhkjh elapsed: 2366,9714 expected: false=False
> - host: 127.0.0.1 elapsed: 4,7249 expected: true=True
>
>Running ping timeout tests timeout = 200. method:ttl+donotfragment (Jimi)
>
> - host: bogusdjfkhkjh elapsed: 2310,836 expected: false actual: False
> - host: 127.0.0.1 elapsed: 0,7838 expected: true actual: True
>
>Running ping timeout tests timeout = 200. method:tasks
>
> - host: bogusdjfkhkjh elapsed: 234,1491 expected: false actual: False
> - host: 127.0.0.1 elapsed: 3,2829 expected: true=True
>
>Running ping timeout tests timeout = 200. method:threads
>
> - host: bogusdjfkhkjh elapsed: 200,5357 expected: false actual:False
> - host: 127.0.0.1 elapsed: 5,5956 expected: true actual: True
注意 对于 Tasks 版本,即使调用线程“未阻塞”,操作本身(在本例中为 ping)也可能会一直持续到实际超时。这就是为什么我建议也为 ping 命令本身设置一个超时时间。
更新也在研究原因,但目前认为解决方法会对您有所帮助。
新发现: