c# -使用Ping事件时应用程序崩溃

本文关键字:应用程序 崩溃 事件 Ping 使用 | 更新日期: 2023-09-27 17:54:04

我正在使用net 3.5中的ping库来检查IP的存在。

请看下面的代码:

    public void PingIP(string IP)
    {
        var ping = new Ping();
        ping.PingCompleted += new PingCompletedEventHandler(ping_PingCompleted); //here the event handler of ping
        ping.SendAsync(IP,"a"); 
    }
void ping_PingCompleted(object sender, PingCompletedEventArgs e)
{
    if (e.Reply.Status == IPStatus.Success)
    {
       //On Ping Success
    }
}

然后我通过Thread或backgroundworker执行代码。

private void CheckSomeIP()
{
        for (int a = 1; a <= 255; a++)
        {
            PingIP("192.168.1." + a);
        }
}
System.Threading.Thread checkip = new System.Threading.Thread(CheckSomeIP);
checkip.Start();

问题是:

如果我启动线程,那么我会关闭应用程序(关闭与控制框在角落),我会得到"应用程序崩溃"

我认为问题是事件处理程序?当我关闭应用程序时,它们仍然在工作,所以我会得到"应用程序崩溃"

解决这个案子的最好方法是什么?

c# -使用Ping事件时应用程序崩溃

我认为,在一个成功的Ping上,你正在尝试从线程内更新接口,这将导致CrossThreadingOperation异常。

在网上搜索ThreadSave/delegate:

public void PingIP(string IP)
{
    var ping = new Ping();
    ping.PingCompleted += new PingCompletedEventHandler(ping_PingCompleted); //here the event handler of ping
    ping.SendAsync(IP,"a"); 
}
delegate void updateTextBoxFromThread(String Text);
void updateTextBox(String Text){
   if (this.textbox1.InvokeRequired){
       //textbox created by other thread.
       updateTextBoxFromThread d = new updateTextBoxFromThread(updateTextBox);
       this.invoke(d, new object[] {Text});
   }else{
      //running on same thread. - invoking the delegate will lead to this part.
      this.textbox1.text = Text;
   }
}
void ping_PingCompleted(object sender, PingCompletedEventArgs e)
{
    if (e.Reply.Status == IPStatus.Success)
    {
       updateTextBox(Text);
    }
}

同样在"退出"应用程序时,您可能希望取消所有正在运行的线程。因此,您需要在应用程序中某个地方启动的每个线程上保持引用。在Main-Form的formclose - event中,你可以强制所有(正在运行的)线程停止。