title: Task Parallel Library - building a tree
body: <p>I'm having trouble with this. I've got "WorkItem" which has a method DoWork. WorkItem can have dependencies which MUST complete before it does, otherwise it throws an exception.</p>
  
  <p>Here's a diagram, where each item (A, B, C, etc.) is a WorkItem. The first items off the rank should thus be A, B, E, as they have no dependencies.</p>
  
  <p><img src="https://i.stack.imgur.com/lZDaD.jpg" alt="Diagram"></p>
  
  <p>So I throw "G" to DoWorkForTask, but my exception throws itself, proving that, say, A and B haven't completed before C runs. The whole tiny project is <a href="http://www.dukecg.net/ThreadedBuilder.zip" rel="nofollow noreferrer">zipped up here.</a></p>
  
  <pre><code>    private void DoWorkForTask(WorkItem item)
      {
          // NOTE: item relies on Dependents to complete before it proceeds
          Task.Factory.StartNew(() =&gt; 
          {
              foreach (var child in item.Dependents)
              {
                  Task.Factory.StartNew(child.DoWork, TaskCreationOptions.AttachedToParent);
  
                  if (child.Dependents.Count &gt; 0)
                      DoWorkForTask(child);
              }
  
              item.DoWork();
          }, TaskCreationOptions.AttachedToParent);
      }
  </code></pre>
  
  <p>Note that I've read <a href="https://stackoverflow.com/questions/4149873/task-parallel-library-for-directory-traversal">this thread</a> and it does not solve the issue.</p>