0

I am using Windows Form application for my thread demo. When I click on button1 ,It will start the thread and recursively doing a work.

Here the Form will not hang as I expected. I want to Stop the currently running thread when I click on Button2. However this won't work.

        private void button1_Click(object sender, EventArgs e)
        {
            t = new Thread(doWork);          // Kick off a new thread
            t.Start();               
        }

        private  void button2_Click(object sender, EventArgs e)
        {                
            t.Abort();
        }    

        static void doWork()
        {    
            while (true)
            {
              //My work    
            }
        }
      }

.When Im debugging, the button2_Click method won't hit the pointer. I think because Thread is keep busy.

Please correct me if I going wrong somewhere.

devan
  • 1,643
  • 8
  • 37
  • 62

1 Answers1

10

You can't kill thread like this. The reason is to avoid situations where you add lock in thread and then kill it before lock is released.

You can create global variable and control your thread using it.

Simple sample:

private volatile bool m_StopThread;

private void button1_Click(object sender, EventArgs e)
{
    t = new Thread(doWork);          // Kick off a new thread
    t.Start();               
}

private  void button2_Click(object sender, EventArgs e)
{                
    m_StopThread = true;
}    

static void doWork()
{    
    while (!m_StopThread)
    {
          //My work    
    }
}
Leri
  • 12,367
  • 7
  • 43
  • 60
  • may be its not a good idea to kill a thread, but its not practical to check your `global variable` every where inside the method especially when the method is too long and doesn't mainly depend on any looping construct.. – techBeginner Oct 15 '12 at 11:35
  • Thank you for reply. but this way is not useful since button2_click method wont hit by the executer. I think this is a problem with something else. – devan Oct 15 '12 at 11:36
  • @devan Button1 starts new thread, when you click button2 you assign variable to something that's visible for your another thread too. what's a problem here? – Leri Oct 15 '12 at 11:41
  • @PLB : When i click button2 ,the button2_click method won't execute. therefore m_StopThread never become true. :( – devan Oct 15 '12 at 11:46
  • @devan If you have button2 and it's click event handler is `button2_Click` why won't it executed? – Leri Oct 15 '12 at 11:48
  • @dotNETbeginner Language designers have decided to do so. By the way, it's not problem create global variables, while deadlocks are. So I think it's a right decision. – Leri Oct 15 '12 at 11:56