title: How to process queued items serially on a low priority thread using Parallel Extensions
body: <p>I want to know what the best way to process the results of a long-running process serially but on a low-priority thread using the <a href="http://msdn.microsoft.com/en-us/library/dd460693.aspx" rel="nofollow">.NET 4.0 Parallel Extensions</a>. </p>
  
  <p>I have the following class that both does the execution and provides the results:</p>
  
  <pre><code>public class Step 
  {
    public string Name { get; set; }
    public TimeSpan Duration { get; set; }
    public bool Completed { get; set; }
  
    public void Execute() 
    {
       DateTime before = DateTime.Now;
       RemotedService.DoSomeStuff();
       Duration = DateTime.Now - before;
       Completed = true;
    }
  }
  </code></pre>
  
  <p>How can I process these steps and also save them to a file, in order, after they are processed?  I would like to save them to a file while <code>RemotedService.DoSomeStuff()</code> is waiting for a response from the server.</p>
  
  <p>Writing to the file would be like this:</p>
  
  <pre><code>using (StreamWriter w = File.AppendText("myFile.txt"))
  {
    var completedStep = completedSteps.Dequeue();
    w.WriteLine(string.Format("Completed {0} with result: {1} and duration {2}", 
                              completedStep.Name, 
                              completedStep.Completed, 
                              completedStep.Duration));
  }
  </code></pre>
  
  <p>One option that comes to mind is to add them to a <code>Queue</code> and have a <code>Timer</code> that processes them.  But this doesn't take advantage of the downtime of the remoted calls.</p>
  
  <p>Another option that comes to mind is to asynchronously write each result to the file using a <code>System.Threading.Tasks.Task</code> per <code>Step</code>, but that doesn't guarantee that they will be saved in order and may also introduce contention with writing to the file.</p>