C#端口扫描仪与Backgroundworker [英] C# Port Scanner with Backgroundworker

查看:94
本文介绍了C#端口扫描仪与Backgroundworker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for (int currPort = firstInterval; firstInterval <= lastInterval; currPort++)
            {
                TcpClient TcpScan = new TcpClient();
                try
                {
                    TcpScan.Connect(ipAddress, currPort);
                    resultTxt.AppendText("Port " + currPort + " open\r\n");
                }
                catch
                {
                    resultTxt.AppendText("Port " + currPort + " closed\r\n");
                }

                if (bgWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }





此代码在

下运行



This code is running under

private void bgWorker_DoWork(object sender, DoWorkEventArgs e)



这并不像我希望的那样真正起作用。它会引发跨线程异常错误。我不太确定如何将字符串发送到结果文本框中。我想可以通过使用ProgressChanged事件来解决。那是我缺少的吗?


which isn''t really working as I was hoping. It throws a cross-thread exception error. I''m not quite sure how to send the string into the result textbox. I''m thinking that it might be possible to solve by using the ProgressChanged event. Is that what I''m missing?

推荐答案

你只需要创建线程安全的调用:

如何:对Windows窗体控件进行线程安全调用 [ ^ ]
You just need to create threadsafe calls:
How to: Make Thread-Safe Calls to Windows Forms Controls[^]


是的,你写的。



当以下行执行时会发生此跨域错误

Yes, you are write.

this cross domain error will occur when the following lines execute
resultTxt.AppendText("Port " + currPort + " open\r\n");
resultTxt.AppendText("Port " + currPort + " closed\r\n");





因为,你将在后台线程中访问主线程控件。

是的,你写的。使用ProgressChanged事件的最佳方式。



以下是代码示例





That because, you are going to access the Main Thread control within the background thread.
Yes, your are write. the best way to use the ProgressChanged event.

Here are the code sample

for (int currPort = firstInterval; firstInterval <= lastInterval; currPort++)
{
  TcpClient TcpScan = new TcpClient();
  try
  {
	TcpScan.Connect(ipAddress, currPort);
	bgWorker.ReportProgress(1, new string[] { currPort.toString() , "open" });                    
  }
  catch
  {                    
	bgWorker.ReportProgress(2, new string[] { currPort.toString() , "closed" });
  }

  if (bgWorker.CancellationPending)
  {
	e.Cancel = true;
	return;
  }
}

private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    var val = e.UserState as string[];
    //index 0 = port number, index 1 = status
     resultTxt.AppendText("Port " + val[0] + " " + val[1] + "\r\n");

}





请注意您必须配置后台工作人员以报告进度如下

bgWorker.WorkerReportsProgress = true;





有关后台工作人员的更多信息,请访问

http ://msdn.microsoft.com/en-us/library/4852et58.aspx [ ^ ]


这篇关于C#端口扫描仪与Backgroundworker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆