C#-使用Ping事件时应用程序崩溃
我正在与Net3.5中的ping Library合作,以检查IP的存在 请看下面的代码:C#-使用Ping事件时应用程序崩溃,c#,multithreading,event-handling,network-programming,ping,C#,Multithreading,Event Handling,Network Programming,Ping,我正在与Net3.5中的ping Library合作,以检查IP的存在 请看下面的代码: public void PingIP(string IP) { var ping = new Ping(); ping.PingCompleted += new PingCompletedEventHandler(ping_PingCompleted); //here the event handler of ping ping.SendAsy
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
}
}
然后我通过线程或backgroundworker执行代码
private void CheckSomeIP()
{
for (int a = 1; a <= 255; a++)
{
PingIP("192.168.1." + a);
}
}
问题是:
如果我启动线程,那么我将关闭应用程序(使用角落处的Controlbox关闭),我将得到“应用程序崩溃”
尽管我已关闭/中止线程。
我认为问题在于事件处理程序?因为当我关闭应用程序时,它们仍在工作,因此我将获得“应用程序崩溃”
解决此问题的最佳方法是什么?我认为,如果Ping成功,您将尝试从线程内更新接口,这将导致CrossThreadingOperation异常 在Web上搜索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);
}
}
同样在“退出”应用程序时,您可能希望取消所有正在运行的线程。因此,您需要在应用程序中某个地方开始的每个线程上保留引用。在主窗体的formClosing事件中,可以强制所有(正在运行的)线程停止。不,我根本没有编写导致“CrossThreadingOperation异常”的代码。我已经把所有的线都合上了,但都不行。因此,我认为事件处理程序是问题所在。你知道吗,如果我们ping不活动的IP,将需要很多时间才能得到他们“超时”而不是活动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");
}
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);
}
}