title: Async Tasks Pause Resume of Loop
body: <p>I have a sample code, taken from MSDN, to which I would like implement the Pause / Resume functionality within while loop. Could anybody propose a solution / parern which would hande this?</p>
  
  <pre><code> private async void startButton_Click(object sender, RoutedEventArgs e)
      {
          resultsTextBox.Clear();
  
          // Instantiate the CancellationTokenSource.
          cts = new CancellationTokenSource();
  
          try
          {
              await AccessTheWebAsync(cts.Token);
              resultsTextBox.Text += "\r\nDownloads complete.";
          }
          catch (OperationCanceledException)
          {
              resultsTextBox.Text += "\r\nDownloads canceled.\r\n";
          }
          catch (Exception)
          {
              resultsTextBox.Text += "\r\nDownloads failed.\r\n";
          }
  
          cts = null;
      }
  
  
      private void cancelButton_Click(object sender, RoutedEventArgs e)
      {
          if (cts != null)
          {
              cts.Cancel();
          }
      }
  
  
      async Task AccessTheWebAsync(CancellationToken ct)
      {
          HttpClient client = new HttpClient();
  
          // Make a list of web addresses.
          List&lt;string&gt; urlList = SetUpURLList();
  
          // ***Create a query that, when executed, returns a collection of tasks.
          IEnumerable&lt;Task&lt;int&gt;&gt; downloadTasksQuery =
              from url in urlList select ProcessURL(url, client, ct);
  
          // ***Use ToList to execute the query and start the tasks. 
          List&lt;Task&lt;int&gt;&gt; downloadTasks = downloadTasksQuery.ToList();
  
          // ***Add a loop to process the tasks one at a time until none remain. 
          while (downloadTasks.Count &gt; 0)
          {
                  // Identify the first task that completes.
                  Task&lt;int&gt; firstFinishedTask = await Task.WhenAny(downloadTasks);
  
                  // ***Remove the selected task from the list so that you don't 
                  // process it more than once.
                  downloadTasks.Remove(firstFinishedTask);
  
                  // Await the completed task. 
                  int length = await firstFinishedTask;
                  resultsTextBox.Text += String.Format("\r\nLength of the download:  {0}", length);
          }
      }
  </code></pre>