title: Long running Process using Task objects and a Monitor Thread
body: <p>I am attempting to monitor a long running process. Right now the process created new Task objects for all the small pieces, but I need some way to monitor their progress to send status to a UI.</p>
  
  <pre><code>ExecutionContext ctx = new ExecutionContext()
          {
              Result = result,
              LastCount = result.Values.Count
          };
  
          Task t = Task.Factory.StartNew(() =&gt;
              {
                  foreach (var dataSlice in dataObjects)
                  {
                     Task.Factory.StartNew(() =&gt;
                     {
                         // Do Some Work
                     }, TaskCreationOptions.AttachedToParent);
                  }
              });
  
          ctx.ParentTask = t;
  
  
          Task monitor = Task.Factory.StartNew( () =&gt;
              {
                  ctx.LastCount = ctx.Result.Values.Count;
  
              }, TaskCreationOptions.LongRunning);
  </code></pre>
  
  <p>My problem, or perhaps question is, if I force my monitor task to wait (via a SpinWait or Sleep) will it possibly lock part of the Tasks created above it? I need the monitor to check status every now and then, but I don't want it's wait condition to kill another task that needs to run.</p>
  
  <p>EDIT:</p>
  
  <p>So I found an interesting approach that's very similar to what Hans suggested in the comments below. It comes in two pieces. One Task to happen multiple times in the middle, and one completion task to do the final clean-up. Still in testing, but it looks promising.</p>
  
  <p>Here's what it looks like:</p>
  
  <pre><code>            Task t = new Task(() =&gt;
              {
                  int i = 0;
                  for (int j = 0; j &lt; 200; j++)
                  {
  
                      foreach (var session in sessions)
                      {
                          Task work = action.Invoke(SomeParameter);
                          if (i == 50 || i == 0)
                          {
                              work.ContinueWith(task =&gt; Task.Factory.StartNew(UpdateAction));
                              i = 1;
                          }
                          else
                          {
                              i++;
                          }
                      }
                  }
              });
  
          ctx.ParentTask = t;
  
          t.ContinueWith(CompletionAction =&gt; Task.Factory.StartNew(() =&gt; CompleteExecution(SomeParameter)));
  
          t.Start();
  </code></pre>