在winfrom程序中加入了网络连接状态检测的方法
MethodTask.Run(() =>
{
toolStripStatusLabel_serverIP.Text = "Server IP:" + StaticModelConfig.serverIP;
int timeout = 2000;//判断超时
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
AutoResetEvent waiter = new AutoResetEvent(false);
PingOptions pOptions = new PingOptions(64, true);
Ping p = new Ping();
do
{
try
{
p.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
p.SendAsync(StaticModelConfig.serverIP, timeout, buffer, pOptions, waiter);
waiter.WaitOne();
if (PublicSwitch.netWorkState.Status == IPStatus.Success)
{
BeginInvoke(new Action(() =>
{
toolStripStatusLabel_state.Text = PublicSwitch.netWorkState.Status.ToString();
toolStripStatusLabel_state.ForeColor = Color.Green;
}));
}
else
{
BeginInvoke(new Action(() =>
{
toolStripStatusLabel_state.Text = PublicSwitch.netWorkState.Status.ToString();
toolStripStatusLabel_state.ForeColor = Color.Red;
}));
}
MethodTask.Delay(1000).Wait();
}
catch (Exception)
{
BeginInvoke(new Action(() =>
{
toolStripStatusLabel_state.Text = "Network port error";
toolStripStatusLabel_state.ForeColor = Color.Red;
}));
}
} while (true);
});
根据设置的MethodTask.Delay(1000).Wait();1000毫秒为间隔,程式在检测网络状态的时候不停的创建cmd窗口
我想知道如何回收这些一次性的cmd窗口
仅供参考:
根据您提供的代码,不断创建cmd窗口可能是在do-while循环中重复调用Ping.SendAsync方法造成的。
避免创建太多 cmd 窗口的一种方法是将 PingCompleted 事件的事件处理程序注册移到循环外。事件处理程序应该只注册一次。
此外,当不再需要 Ping 对象时,最好处理掉它。您可以通过将 Ping 对象包装在 using 语句中来完成此操作。
这是解决这些问题的代码的修改版本:
MethodTask.Run(() =>
{
toolStripStatusLabel_serverIP.Text = "Server IP:" + StaticModelConfig.serverIP;
int timeout = 2000; //判断超时
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
AutoResetEvent waiter = new AutoResetEvent(false);
PingOptions pOptions = new PingOptions(64, true);
using (Ping p = new Ping())
{
p.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
do
{
try
{
p.SendAsync(StaticModelConfig.serverIP, timeout, buffer, pOptions, waiter);
waiter.WaitOne();
if (PublicSwitch.netWorkState.Status == IPStatus.Success)
{
BeginInvoke(new Action(() =>
{
toolStripStatusLabel_state.Text = PublicSwitch.netWorkState.Status.ToString();
toolStripStatusLabel_state.ForeColor = Color.Green;
}));
}
else
{
BeginInvoke(new Action(() =>
{
toolStripStatusLabel_state.Text = PublicSwitch.netWorkState.Status.ToString();
toolStripStatusLabel_state.ForeColor = Color.Red;
}));
}
MethodTask.Delay(1000).Wait();
}
catch (Exception)
{
BeginInvoke(new Action(() =>
{
toolStripStatusLabel_state.Text = "Network port error";
toolStripStatusLabel_state.ForeColor = Color.Red;
}));
}
} while (true);
}
});
除了上面提到的修改之外,此代码还通过将 Ping 对象包装在 using 语句中来处理它。这确保在循环完成或中断时,Ping 对象使用的任何资源都被正确释放。