title: Getting stackoverflow exception with Parallel for each , is this due to thread saftey?
body: <p>I have a foreach loop which works Well . But I want to implement TPL , so did the following:</p>
  
  <pre><code>Parallel.ForEach(fileList, currentfileItem =&gt;
  {
      _clientContext.Load(currentfileItem, w =&gt; w.File);
      _clientContext.ExecuteQuery();
  
      if (currentfileItem.File == null)
      {
          throw new Exception(
              String.Format("File information not found for the item {0}",
                  currentfileItem.DisplayName));
      }
  
      var currentFileName = currentfileItem.File.Name;
  
  
  
      if (!string.IsNullOrEmpty(docRevVersionId))
      {
          var info = Microsoft.SharePoint.Client.File.OpenBinaryDirect(
              _clientContext, currentfileItem["fRef"].ToString());
          if (info != null)
          {
              UpdateToServer(Id, currentFileName, info.Stream);
          }
      }
  
  
  });
  </code></pre>
  
  <p>Once I implement TPL I am getting <code>StackOverflow Exception</code> . I am pretty sure this is because of TPL because without TPL the application runs fine.</p>
  
  <p><code>fileList</code> is <code>IEnumerable&lt;ListItem&gt;</code></p>
  
  <p><strong>Edit:</strong></p>
  
  <p>The SOE probably for this: (VS has ran out of memory to store the exception)
  <img src="https://i.stack.imgur.com/UA21u.png" alt="enter image description here"></p>
  
  <p>and updated code: </p>
  
  <pre><code>Parallel.ForEach(fileList,
                    () =&gt; CreateClientContext(ConfigurationDetails.SharePointUri), //This function creates a new context for the specified url. 
                    (currentfileItem, loopState, localContext) =&gt;
                    {
  
  
                      _clientContext.Load(currentfileItem, w =&gt; w.File);
                      _clientContext.ExecuteQuery();
  
                      if (currentfileItem.File == null)
                      {
                          throw new Exception(String.Format("File information not found for the item {0}", currentfileItem.DisplayName));
                      }
  
                      var currentFileName = currentfileItem.File.Name;
  
  
  
                      if (!string.IsNullOrEmpty(docRevVersionId))
                      {
                          var info = Microsoft.SharePoint.Client.File.OpenBinaryDirect(_clientContext, currentfileItem["fRef"].ToString());
                          if (info != null)
                          {
                              UpdateToServer(Id, currentFileName, info.Stream);
                          }
                      }
  
  
                  },localContext =&gt; localContext.Dispose());
  
   private static ClientContext CreateClientContext(string URI)
          {
              ClientContext context = new ClientContext(URI);
  
              //...Magic...
  
              return context;
          }
  </code></pre>