title: How to cancel execution of a long-running async task in a C# Winforms app
body: <p>I'm a quite inexperienced c# programmer and need help on managing the flow of my program. It is a WinFormApp that asks for multiple user inputs and then uses them to establish serial communication with a device in order to make measurements. The measurements are made in an async method that takes about 20 minutes to run. So I'm using </p>
  
  <pre><code>    void main()
      {
          //Setup
      }
  
      private void button1_Click(object sender, EventArgs e)
      {
          await measurements();
          //Plot results
      }
  
      private async Task measurements()
      {
          while(true){
          //Make some measurements
          await Task.Delay(120000);
          //Make measurements, present data in the UI form.
          //return if done
          }
      }
  </code></pre>
  
  <p>Now I need to make a button which enables the user to cancel the measurements in order to change some input or parameter and then restart the measurements. So I added a "Cancel"-button. </p>
  
  <pre><code>    private void button7_Click(object sender, EventArgs e)
      {
          textBox64.Enabled = true;
          button6.Enabled = true;
          button5.Enabled = true;
          textBox63.Enabled = true;
          button3.Enabled = true;
          trackBar1.Enabled = true;
          timer.Enabled = true;
          button7.Enabled = false;
          clearData();
          // measurement.Stop();            
      }
  </code></pre>
  
  <p>Now I do not know how to manage the flow of the program. I have tried to make a <code>try-catch</code> structure in <code>button1_Click()</code> and throw an Exception from <code>button7_Click</code>, but it doesn't get through to <code>button1_Click()</code>.<br>
  Then I tried to run <code>measurements()</code> on a new thread. But the thread does not have access to 70-ish UI items on my main form.<br>
  And even I wont sink as low as trying Goto. </p>
  
  <p>What I need is advice on how you would program in this situation in order to get a good control of the application and not compromise the flow of the program with risky stuff like exceptions and Goto.</p>