Hi every one!
I am trying to create a port scanner , I would be able to generate numbers of backgroundworker and each bgwork would scan ports simultaneously, but when I generate 10 bgworkers, there is only the last one working ?! I don't know why? but if I re-click the button there is another bgworker come out and working simultaneously, any body know the reason ? please full fill my knowledge!
thank you
Code:private void DoAsSyncScan(int index,int begin = IPEndPoint.MinPort, int end = IPEndPoint.MaxPort) { String ScanAddress; IPAddress ScanIPAddress; startedflg = true; try { ScanAddress = "127.0.0.1"; Action atxtb = () => { if (textBoxIP.Text != string.Empty) ScanAddress = textBoxIP.Text; }; Dispatcher.BeginInvoke(atxtb); // Both a hostname or an IP address are fine if (PortScanning.PortScanning.IsIpAddress(ScanAddress)) { ScanIPAddress = IPAddress.Parse(ScanAddress); } else if (!PortScanning.PortScanning.LookupDNSName(ScanAddress, out ScanIPAddress)) { MessageBox.Show("Error looking up {0}", ScanAddress); return; } // Report what we are going to do // Scan all the possible posts for (int Port = begin; Port < end; Port++) { //invoke the dispatcher and pass the percentage and max record count Action act1 = () => { this.UpdateProgressText(index, (begin - begin / end - begin) * 100, end - begin, Port); }; Dispatcher.BeginInvoke(act1); var r = dt.NewRow(); if (PortScanning.PortScanning.ScanPort(ScanIPAddress, Port)) { r["Port"] = Port + ""; r["Status"] = "Opened"; Action act2 = () => { dt.Rows.Add(r); }; //Parallel.Invoke(act2); Dispatcher.BeginInvoke(act2); } System.Threading.Thread.Sleep(10); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } BackgroundWorker[] bgworkers; System.Data.DataTable dt = new System.Data.DataTable(); private void buttonScan_Click(object sender, RoutedEventArgs e) { try { bgworkers = new BackgroundWorker[(int)this.decimalUpDownThread.Value]; int part = (int)Math.Ceiling((double)IPEndPoint.MaxPort / (double)this.decimalUpDownThread.Value); int begin = 0; Action act0 = () => { this.dataGrid1.DataContext = dt.DefaultView; }; Dispatcher.BeginInvoke(act0); for (; begin < bgworkers.Length; begin++) { bgworkers[begin] = new BackgroundWorker(); bgworkers[begin].WorkerSupportsCancellation = true; DoJobs( bgworkers[begin], begin, part); } foreach (var item in bgworkers) { item.RunWorkerAsync(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } public void DoJobs(BackgroundWorker bgx,int begin,int part) { bgx.DoWork += (wsender, we) => { System.Console.WriteLine("started:{0}",we.Argument); if (IPEndPoint.MaxPort > (begin + 1) * part) DoAsSyncScan(begin, begin * part, begin * part); else DoAsSyncScan(begin, begin * part, IPEndPoint.MaxPort); }; //System.Threading.Thread.Sleep(1000); }


Reply With Quote

Bookmarks