1

I start a thread when pressing on start button which start a delay timer and then show a messageBox dialog. Now, I'm trying to stop this thread, but I can't find a way for that, except add a flag which will prevent the thread to display the messageBox dialog but not to kill the thread. I would appreciate if you can suggest a way to KILL the thread.

Thanks Moti

public partial class Form1 : Form
{
    public delegate void example();
    ThreadA threadA = null;

    public Form1()
    {
        InitializeComponent();
    }

    example ex;
    IAsyncResult result;
    private void button_Start_Click(object sender, EventArgs e)
    {
            ex = new example(start);//.BeginInvoke(null, null);
            result = ex.BeginInvoke(null, null);
    }

    private void button_Stop_Click(object sender, EventArgs e)
    {
        if (threadA != null)
            threadA = null;
    }

    private void start()
    {
        if (threadA == null)
        {
            threadA = new ThreadA();
            threadA.run();
        }
    }

}




class ThreadA
{
    //public event
    public Boolean flag = false;
    public void run()
    {
        Thread.Sleep(15000);
        MessageBox.Show("Ended");
    }
}
Alex
  • 7,901
  • 1
  • 41
  • 56
Moti
  • 897
  • 4
  • 12
  • 21
  • possible duplicate of [How to kill a thread instantly in C#?](http://stackoverflow.com/questions/1327102/how-to-kill-a-thread-instantly-in-c) – James Nov 23 '11 at 08:46

2 Answers2

1

I'd Use the Task Class with a CancellationTokenSource.

 CancellationTokenSource cts = new CancellationTokenSource();
 Task t = new Task(() => new ThreadA().run(cts.Token), cts.Token); 

  // Start
  t.Start();
  ShowMessageBox(cts)

Edit2: to your Comment:

void ShowMessageBox(CancellationTokenSource cts)
{ 
    if(MessageBox.Show("StopThread",
    "Abort",MessageBoxButtons.YesNo,
     MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
    {
      cts.Cancel();
  }       
}
Alex
  • 7,901
  • 1
  • 41
  • 56
  • Seems to me, this solution kill the MessageBox but not the thread (ThreadA). Am I right? Because I meant that pressing on the STOP button will kill the thread even it in delay of 15 seconds. – Moti Nov 23 '11 at 09:14
0

Use ManualResetEvent

class ThreadA
{
    ManualResetEvent _stopEvent = new ManualResetEvent(false);
    Thread _thread;

    public Boolean flag = false;
    public void run()
    {
        while (true)
        {
            if (_stopEvent.Wait(15000))
                return; // true = event is signaled. false = timeout

            //do some work
        }

        MessageBox.Show("Ended");
    }

    public void Start()
    {
        _stopEvent.Reset();
        _thread = new Thread(run);
        _thread.Start();
    }

    public void Stop()
    {
        _stopEvent.Set();
        _thread.Join();
        _thread = null;
    }
}

However, I would use a Timer if the thread is not going to do work all the time.

jgauffin
  • 99,844
  • 45
  • 235
  • 372