0

I tried to make a new thread using the winform application. Here is my sample code.

public static bool stop = false;

private Thread mythread(){
    Thread t = new Thread(delegate() {
        while(!stop){
             // Something I want to process
        }
    });
return t;
}

private Button1_click(object sender, EventArgs e){
    stop = true; // I know it doesn't work

    this.Dispose();
    this.Close();
}

public Main(){
   InitializeComponent();

   Thread thread = mythread();
   thread.Start();
}

When the button1 is clicked, new thread and winform should be terminated, but new thread is still working. Is there any way to terminate the new thread?

ps: I tried to change my code reffering to the MSDN site example but it only made it more complicated.

Nayantara Jeyaraj
  • 2,624
  • 7
  • 34
  • 63
jaeseung you
  • 33
  • 1
  • 8
  • If there is a long process in the while loop, it will take time to exit it. Checking every few commands whether to stop or not is better. You can always use tasks to achieve this goal. Tasks has better cancellation mechanism. – Inbar Barkai Oct 11 '16 at 04:10
  • You are not doing this correctly, non-zero odds that the thread will *never* stop. Just do this the right way. – Hans Passant Oct 11 '16 at 05:10

1 Answers1

0

This is a problem of visibility of variables in other threads... try this:

private static int stop = 0;

private Thread mythread(){
    Thread t = new Thread(delegate() {
        while(Thread.VolatileRead(ref stop) == 0){
             // Something I want to process
        }
    });
return t;
}

private Button1_click(object sender, EventArgs e){
    Thread.VolatileWrite(ref stop, 1);

    this.Dispose();
    this.Close();
}

public Main(){
   InitializeComponent();

   Thread thread = mythread();
   thread.Start();
}

Notes:

Theraot
  • 31,890
  • 5
  • 57
  • 86