title: Thread safe StreamWriter C# how to do it? 2
body: <p>So this is a continuation from my last question - So the question was
  "What is the best way to build a program that is thread safe in terms that it needs to write double values to a file. If the function that saves the values via streamwriter is being called by multiple threads? Whats the best way of doing it?"</p>
  
  <p>And I modified some code found at MSDN, how about the following? This one correctly writes everything to the file.</p>
  
  <pre><code>namespace SafeThread
  {
      class Program
      {
          static void Main()
          {
              Threading threader = new Threading();
  
              AutoResetEvent autoEvent = new AutoResetEvent(false);
  
              Thread regularThread =
                  new Thread(new ThreadStart(threader.ThreadMethod));
              regularThread.Start();
  
              ThreadPool.QueueUserWorkItem(new WaitCallback(threader.WorkMethod),
                  autoEvent);
  
              // Wait for foreground thread to end.
              regularThread.Join();
  
              // Wait for background thread to end.
              autoEvent.WaitOne();
          }
      }
  
  
      class Threading
      {
          List&lt;double&gt; Values = new List&lt;double&gt;();
          static readonly Object locker = new Object();
          StreamWriter writer = new StreamWriter("file");
          static int bulkCount = 0;
          static int bulkSize = 100000;
  
          public void ThreadMethod()
          {
              lock (locker)
              {
                  while (bulkCount &lt; bulkSize)
                      Values.Add(bulkCount++);
              }
              bulkCount = 0;
          }
  
          public void WorkMethod(object stateInfo)
          {
              lock (locker)
              {
                  foreach (double V in Values)
                  {
                      writer.WriteLine(V);
                      writer.Flush();
                  }
              }
              // Signal that this thread is finished.
              ((AutoResetEvent)stateInfo).Set();
          }
      }
  }
  </code></pre>