【发布时间】:2016-01-27 08:55:00
【问题描述】:
我正在使用 Ping 类定期 ping 几个主机。如果下一次 ping 的时间到了,但上一次 ping 还没有完成,我会调用 SendAsyncCancel 来终止它。
如果我禁用网络接口,就会出现问题。在这种情况下,异步回调永远不会被调用,并且对 SendAsyncCancel 的调用永远不会返回。
更多信息:我在 Windows 7 x64 上使用 .net 3.5 和 C# VS2008 express。我从表单的 Timer.Tick 回调中调用 ping。我为每台主机只创建一次 Ping 类(总共 3 台主机,但只有一台主机相同)。超时为 5 秒。问题是 100% 可重复的。
我发现的只是多个创建/销毁 ping 类的 ping 崩溃问题,但这不是我的情况。
using System;
using System.Net.NetworkInformation;
using System.Windows.Forms;
namespace TestPing {
public partial class Form1 : Form {
private Ping Pinger;
public Form1()
{
InitializeComponent();
Pinger = new Ping();
Pinger.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
}
private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
txtResult.Text = e.Cancelled ? "Cancelled" : e.Reply.Status.ToString();
}
private void butSend_Click(object sender, EventArgs e)
{
txtResult.Text = "(result)";
txtStatus.Text = "SendAsync() calling...";
Pinger.SendAsync(txtHost.Text, null);
txtStatus.Text = "SendAsync() done.";
}
private void butCancel_Click(object sender, EventArgs e)
{
txtStatus.Text = "SendAsyncCancel() calling...";
Pinger.SendAsyncCancel();
txtStatus.Text = "SendAsyncCancel() done.";
}
}
}
【问题讨论】:
-
您能否发布相同的示例代码或将确切的代码提取到单独的测试应用程序中,以便我们进行调查?
-
我创建了一个空项目来复制并发布它的代码。我还注意到,如果我在 ping 不存在的主机(但已连接网络)时使用 SendAsyncCancel,它只会在 ping 超时期限过去后才取消,而不是立即取消。所以问题的根源可能是在取消之前等到完成。