读书人

c#多线程端口扫描,该怎么解决

发布时间: 2012-01-29 21:39:32 作者: rapoo

c#多线程端口扫描
哪个朋友帮我调试一下面的代码~!谢谢~!,随便问一下,朋友有没人c#多线程方面的电子书~!我的邮箱lybyt130@163.com
我在这里先说谢谢了~!
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace 端口扫描器
{
   /// <summary>
   /// Form1 的摘要说明。
   /// </summary>
   public class MainApp : System.Windows.Forms.Form
   {
      private System.Windows.Forms.Label lblAddr;
      private System.Windows.Forms.Label label1;
      private System.Windows.Forms.Label label2;
      private System.Windows.Forms.TextBox txtAddr;
      private System.Windows.Forms.TextBox txtStart;
      private System.Windows.Forms.TextBox txtEnd;
      private System.Windows.Forms.ProgressBar progressBar1;
      private System.Windows.Forms.Button btnScan;
      private System.Windows.Forms.ListBox lbResult;
      
      //定义私有变量
      private int port;
      private string Addr;
      private bool[] done =new bool[65536];
      private int start;
      private int end;
      private Thread scanThread;
      private bool OK;
      private int i;
      private System.Windows.Forms.Label lblStart;
      private System.Windows.Forms.Label lblNow;
      private System.Windows.Forms.Label lblStop;
      private System.Windows.Forms.Label label3;
      private System.Windows.Forms.StatusBar statusBar1;
      private System.Windows.Forms.StatusBarPanel statusBarPanel2;


      /// <summary>
      /// 必需的设计器变量。
      /// </summary>
      private System.ComponentModel.Container components = null;

      public MainApp()
      {
         //
         // Windows 窗体设计器支持所必需的
         //
         InitializeComponent();

         //
         // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
         //
      }

      /// <summary>
      /// 清理所有正在使用的资源。
      /// </summary>
      protected override void Dispose( bool disposing )
      {
         if( disposing )
         {
            if (components != null)
            {
               components.Dispose();
            }
         }
         base.Dispose( disposing );
      }

      #region Windows 窗体设计器生成的代码

[解决办法]
终于调试通过了
本来我向通过委托来使用线程安全的访问控件,但是似乎楼主的东东起了太多的线程,导致堆栈溢出了。

最后通过一个简单的方法解决了
就是在InitializeComponent方法中加上一句:
MainApp.CheckForIllegalCrossThreadCalls = false;
不检测从线程来的非法调用就ok了

还有一个问题就是楼主对每一个端口都起了一个线程去扫描,这样速度肯定没有单线程的快,因为线程之间的切换还需要时间

解决办法就是添加一个线程数的输入框
主线程在启动扫描子线程的时候只启动相应线程数的扫描子线程

每个子线程开始扫描端口依次递加,步长为线程数

线程0扫描端口 start + 0 ,start + threadNum + 0 ,…… ,到end结束
线程1扫描端口 start + 1 ,start + threadNum + 1 ,…… ,到end结束


线程2扫描端口 start + 2 ,start + threadNum + 2 ,…… ,到end结束
线程3扫描端口 start + 3 ,start + threadNum + 3 ,…… ,到end结束
……
线程threadNum扫描端口 start + threadNum , start + threadNum + threadNum , …… ,到end结束

这样的话就没问题了

楼主如果还有什么问题我们继续讨论

读书人网 >C#

热点推荐