title: Streamwriter, StringBuilder and Parallel loops
body: <p>Sorry for big chunk of code, I couldn't explain that with less.Basically I'm trying to write into a file from many tasks. 
  Can you guys please tell me what I'm doing wrong? <code>_streamWriter.WriteLine()</code> throws the <code>ArgumentOutOfRangeException</code>.</p>
  
  <pre><code>class Program
  {
      private static LogBuilder _log = new LogBuilder();
      static void Main(string[] args)
      {
          var acts = new List&lt;Func&lt;string&gt;&gt;();
          var rnd = new Random();
          for (int i = 0; i &lt; 10000; i++)
          {
              acts.Add(() =&gt;
              {
                  var delay = rnd.Next(300);
                  Thread.Sleep(delay);
                  return "act that that lasted "+delay;
              });
          }
  
          Parallel.ForEach(acts, act =&gt;
          {
              _log.Log.AppendLine(act.Invoke());
              _log.Write();
          });
      }
  }
  
  public class LogBuilder : IDisposable
  {
      public StringBuilder Log = new StringBuilder();
      private FileStream _fileStream;
      private StreamWriter _streamWriter;
  
      public LogBuilder()
      {
          _fileStream = new FileStream("log.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
          _streamWriter = new StreamWriter(_fileStream) { AutoFlush = true };
      }
      public void Write()
      {
          lock (Log)
          {
              if (Log.Length &lt;= 0) return;
              _streamWriter.WriteLine(Log.ToString()); //throws here. Although Log.Length is greater than zero
              Log.Clear();
          }
      }
  
      public void Dispose()
      {
          _streamWriter.Close(); _streamWriter.Dispose(); _fileStream.Close(); fileStream.Dispose();
      }
  }
  </code></pre>