1

I have created a thread for my ip scanner application. Now when the user click the start button, it will start the thread, do scan and generate ID.

ID | printer_ip
---------------  
 1 | 10.0.0.0  
 2 | 10.0.0.1
 3 | 10.0.0.2

But the problem is that when the user want to re-click the start button again to rescan before the previous process finish, it looks like the ID become mess.

ID | printer_ip
---------------    
 1 | 10.0.0.0  
 4 | 10.0.0.3
 2 | 10.0.0.1

I notice that this is because the old thread is still running while the new thread is running. Therefore how to kill the old thread whenever the user re-click the start scan button? can I use Thread.Abort() method? If yes, where should I place it?

     private void StartClick(object sender, System.EventArgs e)
     {
        sercher = new Thread(new ThreadStart(Serche));
        try
        {
            IPAddress from = IPAddress.Parse(ipFrom.Text);
            IPAddress to = IPAddress.Parse(ipTo.Text);
        }
        catch (FormatException fe)
        {
            MessageBox.Show(fe.Message);
            return;
        }
        sercher.Name = "Network searching thread";
        sercher.Start();
        //add.Items.Add("-->> >>> Please wait while processing is done <<< <<--");
        Thread.Sleep(1);
    }
Ren
  • 765
  • 4
  • 15
  • 42

1 Answers1

3

The correct way to kill a thread is to use a flag. You check the flag in the thread, and quit it if it raised. For example:

while (!IsCancelled)
{
  //Scan a single IP here...
}

When you click "Start" again, you should first raise the flag (IsCancelled = true), call Thread.Join to wait for that thread to stop, and only then start the thread again.

P.S. Do not be tempted to use Thread.Abort! This is very, very bad.

Nick
  • 4,787
  • 2
  • 18
  • 24
  • Why Thread.Abort is very very bad?? while you have in mind that Thread.Abort will raise a ThreadAbortedException everything should be fine – Gusman May 30 '14 at 08:50
  • but if I use the flag, is the apps still need to wait the old thread to complete then only it will restart a new thread? then the user will need to take some time after re-click the start button correct me if im wrong. – Ren May 30 '14 at 08:51
  • 1
    Check [this post](http://stackoverflow.com/a/458193/17034) to see why your answer is such a **very**, **very** bad idea. – Hans Passant May 30 '14 at 09:04
  • Gusman, Thread.Abort will terminate the thread at any unknown point, and there will be no one to remove the dead bodies. In other words, all the data will be in undefined state, and there is chance the application will not be able to continue safely. – Nick May 30 '14 at 14:57