title: C# Parallel.For to create array: OK to put lock() on the array?
body: <p>I have a time-consuming static C# method for creating an array (of <code>double</code>:s) and have therefore parallelized the operation. </p>
  
  <p>Since I am creating the array before entering the loop and not tampering with its reference after that, I am thinking that it should be sufficient to <code>lock</code> the array itself while updating it within the parallel loop.</p>
  
  <p>Is it OK to <code>lock</code> on the array itself or would I potentially face some performance or deadlock problems with this approach? Is it better to create a separate <code>lock</code> variable to put the lock on?</p>
  
  <p>Here is some sample code to illustrate:</p>
  
  <pre><code>static double[] CreateArray(int mn, int n)
  {
    var localLock = new object();    // Necessary?
    var array = new double[mn];
  
    Parallel.For(0, n, i =&gt;
    {
      ... lengthy operation ...
  
      lock (array)    // or is 'lock (localLock)' required?
      {
        UpdatePartOfArray(array);
      }
    });
  
    return array;
  }
  </code></pre>