0

I'd like to run one function or both functions A and B at the same time depending if corresponding checkboxes c_A and c_B are chcecked or not. I'd also like to stop all (one or two) running functions by cliking stop button. I tried following code. It wokrs when only one chceck box is chcecked. When both chceckboxes are chcecked just function A runs. The running function doesn't stop when I press the stop button.

private void Start_Click(object sender, EventArgs e)
        {       
       ThreadStart ts_A = delegate()
                {
                };
                if (c_A.Checked)
                {
                    t_A = new Thread(ts_A);
                    t_A.Start();
                    function_A();
                }

                   ThreadStart ts_B = delegate()
                {
                };
                if (c_B.Checked)
                {
                    t_B = new Thread(ts_B);
                    t_B.Start();
                    function_B();
                }
         }

       private void Stop_Click(object sender, EventArgs e)
       {
           t_A.Abort();
           t_B.Abort();
        }
kamila
  • 122
  • 1
  • 2
  • 13
  • Your `ts_A` and `ts_B` are pointing to empty delegates. Which does not do anything useful. if you wanted to call `function_a` and `function_b` be executed in corresponding thread then wrap a call statement in those delegate. – Jenish Rabadiya Apr 03 '15 at 05:40
  • 1
    Please **never** call `Abort()` on a thread unless you are in the process of shutting down your app. Calling it is dangerous otherwise. Have a read of this: http://stackoverflow.com/a/1560567/259769 – Enigmativity Apr 03 '15 at 06:04
  • Please see ["Should questions include “tags” in their titles?"](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles), where the consensus is "no, they should not"! –  Apr 03 '15 at 06:43

1 Answers1

1

You are not calling your methods in a Thread at all. You are actually calling it out of the Thread.

In order for it to be called within the thread, the method should be passed within ThreadStart.

ThreadStart ts_A = new ThreadStart(function_A);

Then calling t_A.Start would run the function_A in a thread. You can find more information on ThreadStart here https://msdn.microsoft.com/en-us/library/system.threading.threadstart%28v=vs.110%29.aspx

Having said that, your method should look like this.

private void Start_Click(object sender, EventArgs e)
    {       
   ThreadStart ts_A = new ThreadStart(function_A);
            if (c_A.Checked)
            {
                t_A = new Thread(ts_A);
                t_A.Start();

            }

               ThreadStart ts_B = new ThreadStart(function_B);
            if (c_B.Checked)
            {
                t_B = new Thread(ts_B);
                t_B.Start();

            }
     }
Praveen Paulose
  • 5,741
  • 1
  • 15
  • 19