title: How to handle Parallel Execution C# for Database connection
body: <p>I have following code which will fire query on each database in SQL SERVER 2008R2,</p>
  
  <pre><code>public DataTable GetResultsOfAllDB(string query)
          {
              SqlConnection con = new SqlConnection(_ConnectionString);
              string locleQuery = "select name from [master].sys.sysdatabases";
              DataTable dtResult = new DataTable("Result");
              SqlCommand cmdData = new SqlCommand(locleQuery, con);
              cmdData.CommandTimeout = 0;
  
              SqlDataAdapter adapter = new SqlDataAdapter(cmdData);
              DataTable dtDataBases = new DataTable("DataBase");
              adapter.Fill(dtDataBases);
  
              // This is implemented for sequential           
              foreach (DataRow drDB in dtDataBases.Rows)
              {
                  locleQuery = " Use [" + Convert.ToString(drDB[0]) + "]; " + query;
                  cmdData = new SqlCommand(locleQuery, con);
                  adapter = new SqlDataAdapter(cmdData);
                  DataTable dtTemp = new DataTable();
                  adapter.Fill(dtTemp);
                  dtResult.Merge(dtTemp);
              }
  
              //Parallel Implementation
              Parallel.ForEach(dtDataBases.AsEnumerable(), drDB =&gt;
                  {
                      locleQuery = " Use [" + Convert.ToString(drDB[0]) + "]; " + query;
                      con = new SqlConnection(_ConnectionString);
                      cmdData = new SqlCommand(locleQuery, con);
                      cmdData.CommandTimeout = 0;
                      adapter = new SqlDataAdapter(cmdData);
                      DataTable dtTemp = new DataTable();
                      adapter.Fill(dtTemp);
                      dtResult.Merge(dtTemp);
                  }
              );
  
              return dtResult;
  
          }
  </code></pre>
  
  <p>Now the problem is when i use the second loop i.e. <code>Parallel ForEach</code> loop it gives me different errors at the line <code>adapter.Fill(dtTemp);</code> as following, </p>
  
  <p>Yes of-course these are expected errors.</p>
  
  <ol>
  <li>Connection is closed</li>
  <li>Connection is opening,</li>
  <li>Data reader is closed</li>
  <li>reader is connecting..
  Blha Blha ... All connection related errors.</li>
  </ol>
  
  <p>Note : Some time it works like charm i mean no errors.</p>
  
  <p>And absolutely the first loop i.e. Sequential <code>foreach</code> loop works fine but the performance is not that good looking which i fall in Love with it :)</p>
  
  <p>Now my question is if i want to use <code>parallel foreach</code> loop for the same, then How should i do this? Is there any cosmetics which will help the Parallel Foreach loop good looking ;)</p>
  
  <p>Thanks in Advance.</p>