title: C# Stop Thread using button after thread finished current function loop
body: <p>I have a Windows form application which uses a start button to perform an infinite loop. I have a stop button which I am attempting to use to stop the infinite loop after the loop has completed a cycle.</p>
  <p>I have attempted to use thread.Interrupt which doesn't allow the loop to finish.</p>
  <p>I have also used thread.abort which obviously doesn't allow the loop to finish.</p>
  <p>I have also attempted to do this by having the stop button update a global variable which the while loop inside my thread is reliant on but the global variable does not update inside the thread.</p>
  <p>main class code</p>
  <pre><code>startbutton()
  {
    handle = getHandle();
    Loopclass.loopclass loop = new Loopclass.loopclass(handle);
    thread = new Thread(()=&gt;loop.run());
    thread.Start();
  }
  
  stopbutton()
  {
    handle = getHandle();
    Loopclass.loopclass loop = new Loopclass.loopclass(handle);
    loop.setCh();
  }
  </code></pre>
  <p>Loop Class code</p>
  <pre><code>//_ch is a global string variable
  Run()
  {
    while(_ch != &quot;X&quot;)
    {
      //do stuff
      string x = &quot;&quot;;
      _ch = getCh(x);
    }
  }
  
  setCh()
  {
    _ch = &quot;X&quot;;
  }
    
  getCh(string x)
  {
    x = &quot;X&quot;;
    return x;
  }
  </code></pre>