title: Run tasks serially on one thread
body: <p>I have several threads (doing server work) that need to queue work to be done on the main thread (they need access to an API which can only be called from the main thread).</p>
  <p>Using the Task system makes sense to me, as the server threads can produce tasks which use this main-thread-only API, queue them to run on the main thread and await them.  The main thread can spin, popping tasks from a ConcurrentQueue and run them as they come in.</p>
  <p>Essentially this is a bit of an inversion of the usual pattern, where tasks are run in parallel across a thread pool.  Here, the Tasks are created from multiple other threads and queued up to run on the one main thread.</p>
  <p>Now for a wrinkle: some of these tasks might spawn sub tasks which themselves need to be run on the main thread.  eg:</p>
  <pre><code># On server thread:
  Task taskA = new Task(async () =&gt; {
    Task taskB = new Task(() =&gt; Console.WriteLine(&quot;some sub work&quot;));
    MainThreadWorkQueue.BeginInvoke(taskB);
    await taskB;
  });
  MainThreadWorkQueue.BeginInvoke(taskA);
  await taskA;
  </code></pre>
  <p>This might be because one of the top level tasks is using library code which itself needs to run on the main thread.</p>
  <p>So I end up with a tree-like structure of Tasks, where root level tasks need to block waiting on leaf tasks to finish, but the root tasks are also creating these leaf tasks dynamically as they execute.</p>
  <p>The problem is I'm not sure how to write the main thread code.  I was thinking something like:</p>
  <pre><code>// Main thread:
  while(true) {
    Task currentTask;
    while (MainThreadWorkQueue.TryDequeue(out currentTask)) {
      currentTask.Wait();
    }
  
    // Do other work
  }
  </code></pre>
  <p>However this will deadlock in the taskA example above, as taskB gets queued but taskA will never finish to allow taskB's work to begin.</p>
  <p>Ideally I'd like to do something like:</p>
  <pre><code>// Main thread:
  while(true) {
    Task currentTask;
    while (MainThreadWorkQueue.TryDequeue(out currentTask)) {
      currentTask.RunUntilFinishedOrBlocked();
      if (currentTask.IsBlockedOnOtherTask) {
        MainThreadWorkQueue.Enqueue(currentTask)
      }
    }
  
    // Do other work
  }
  </code></pre>
  <p>Is there a way to run a task until it's blocked on another task?  Or a different way to approach this problem?</p>