繁体   English   中英

C#-使用Ping事件时应用崩溃

[英]C# - App Crash When Using Ping event

我正在与ping Librarry在net 3.5中合作,以检查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(); 

好吧,这是问题所在:

如果我启动线程,则我将关闭应用程序(在角落使用Controlbox关闭),尽管我已关闭/中止线程,但仍会收到“ App Crash”。

我认为问题是事件处理程序? 因为当我关闭应用程序时它们仍在工作,因此我将收到“ App Crash”

解决这种情况的最佳方法是什么?

我认为,在成功的Ping上,您正在尝试从Thread内部更新接口,这将导致CrossThreadingOperation异常。

在网上搜索ThreadSave /委托:

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);
    }
}

同样在“退出”应用程序时,您可能要取消所有正在运行的线程。 因此,您需要在您的应用程序中某个地方启动的每个线程上保留引用。 在主窗体的formClosing-Event中,可以强制所有(正在运行的)线程停止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM