title: .NET async, can a single thread time-slice between tasks?
body: <p>I'm trying to get a grasp on asynchronous programming in C#/.NET.  I read an article (<a href="http://cs.brown.edu/courses/cs168/f12/handouts/async.pdf" rel="nofollow">link</a>) on Brown University's website for the cs168 course that defines asynchronous programming as interleaving tasks within the same thread. It says, "Now we can introduce the asynchronous model... In this model, the tasks are interleaved with one another, but in a single thread of control", and shows interleaving very clearly in a figure.  But I can't seem to get two tasks to interleave within the same thread in .NET.  Is there a way to do that?</p>
  
  <p>I wrote some simple apps to try to test this theory, but I'm not sure if I'm doing it correctly.  The main program outputs to the screen every so often, using <code>Thread.Sleep()</code> to simulate work.  The asynchronous task does the same.  If multiple threads are used, the output is interleaved. But I'm trying to test on a single thread.</p>
  
  <p>I have a WPF app that runs everything on the UI thread, but the task and main program always output sequentially. I create and start the task like this:</p>
  
  <pre><code>var taskFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
  var task = taskFactory.StartNew(workDelegate);
  </code></pre>
  
  <p>I have a console app that starts the task delegate using <code>Task.Run(workDelegate);</code>, but that runs them on different thread pool threads. I'm not sure how to make them both run on the same thread.  If I try the same approach I used in WPF I get a runtime InvalidOperationException, "The current SynchronizationContext may not be used as a TaskScheduler".</p>