Ren
Ren

Reputation: 775

Kill old thread and start new thread in System.Threading

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);
    }

Upvotes: 1

Views: 810

Answers (1)

Nick
Nick

Reputation: 5042

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.

Upvotes: 3

Related Questions