title: C# Parallel library, XmlReader, XmlWriter
body: <p>I have a use case where I need to:</p>
  
  <ul>
  <li>iterate through each Input node in an Xml document</li>
  <li>perform a time-intensive calculation on each Input, and </li>
  <li>write the results to an XML file.</li>
  </ul>
  
  <p>Input looks something like this:</p>
  
  <pre><code>&lt;Root&gt;
    &lt;Input&gt;
      &lt;Case&gt;ABC123&lt;/Case&gt;
      &lt;State&gt;MA&lt;/State&gt;
      &lt;Investor&gt;Goldman&lt;/Investor&gt;
    &lt;/Input&gt;
    &lt;Input&gt;
      &lt;Case&gt;BCD234&lt;/Case&gt;
      &lt;State&gt;CA&lt;/State&gt;
      &lt;Investor&gt;Goldman&lt;/Investor&gt;
    &lt;/Input&gt;
  &lt;/Root&gt;
  </code></pre>
  
  <p>and the output:</p>
  
  <pre><code>&lt;Results&gt;
    &lt;Output&gt;
      &lt;Case&gt;ABC123&lt;/Case&gt;
      &lt;State&gt;MA&lt;/State&gt;
      &lt;Investor&gt;Goldman&lt;/Investor&gt;
      &lt;Price&gt;75.00&lt;/Price&gt;
      &lt;Product&gt;Blah&lt;/Product&gt;
    &lt;/Output&gt;
    &lt;Output&gt;
      &lt;Case&gt;BCD234&lt;/Case&gt;
      &lt;State&gt;CA&lt;/State&gt;
      &lt;Investor&gt;Goldman&lt;/Investor&gt;
      &lt;Price&gt;55.00&lt;/Price&gt;
      &lt;Product&gt;Ack&lt;/Product&gt;
    &lt;/Output&gt;
  &lt;/Results&gt;
  </code></pre>
  
  <p>I would like to run the calculations in parallel; the typical input file may have 50,000 input nodes, and the total processing time without threading may be 90 minutes. Approximately 90% of the processing time is spent on step #2 (the calculations).</p>
  
  <p>I can iterate over the <a href="http://msdn.microsoft.com/en-us/library/bb387035.aspx" rel="noreferrer">XmlReader in parallel</a> easily enough:</p>
  
  <pre><code>static IEnumerable&lt;XElement&gt; EnumerateAxis(XmlReader reader, string axis)
  {
    reader.MoveToContent();
    while (reader.Read())
    {
      switch (reader.NodeType)
      {
        case XmlNodeType.Element:
          if (reader.Name == axis)
          {
            XElement el = XElement.ReadFrom(reader) as XElement;
            if (el != null)
              yield return el;
          }
          break;
      }
    }
  }
  ...
  Parallel.ForEach(EnumerateAxis(reader, "Input"), node =&gt;
  { 
    // do calc
    // lock the XmlWriter, write, unlock
  });
  </code></pre>
  
  <p>I'm currently inclined to use a lock when writing to the XmlWriter to ensure thread safety.</p>
  
  <p>Is there a more elegant way to handle the XmlWriter in this case? Specifically, should I have the Parallel.ForEach code pass the results back to the originating thread and have that thread handle the XmlWriter, avoiding the need to lock? If so, I'm unsure of the correct approach for this.</p>