我有这个方法来发送ping一段时间。
public async Task<bool> TryToConnect(bool firstTime, int second)
{
var valueToReturne = false;
if (firstTime)
await Task.Delay(1200);
var ct = new CancellationTokenSource(TimeSpan.FromSeconds(second)).Token;
var pingSender = new Ping();
PingReply result;
try
{
while (!ct.IsCancellationRequested)
{
result = await pingSender.SendPingAsync("www.google.com", 100);//null exeption
if (result.Status != IPStatus.Success)
continue;
valueToReturne = true;
break;
}
}
catch (Exception)
{
valueToReturne = await TryToConnect(false, second / 2);
}
return valueToReturne;
}
出于我不知道的原因。
result = await pingSender.SendPingAsync("www.google.com", 100);
命令有时没有互联网访问经历空异常和方法将用于 CT 的捕获块结束,但我想执行
result = await pingSender.SendPingAsync("www.google.com", 100);
在任何情况下指挥 CT 持续时间。
即使第一个 ping 返回异常,ping 也会保持异步重试。因此,需要注册 ping 已完成事件,以便您知道 ping 在超时之前正在重试。请在下面找到代码:
private void Form1_Load(object sender, EventArgs e)
{
var result = TryToConnect();
}
private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
if (e.Cancelled)
return;
if (e.Error != null)
return;
if (e.Reply.Status == IPStatus.Success)
{
}
}
private bool TryToConnect()
{
Ping myPing = new Ping();
int timeOutMS = 5000; //5 seconds
myPing.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
try
{
myPing.SendAsync("www.google.com", timeOutMS);
return true;
}
catch
{
return false;
}
}