title: C# Parallel.For and Oracle database access - memory exception
body: <p>I am working on some code that I would like to access an Oracle database inside of a <code>Parallel.For</code> loop. The loop will run for several minutes, and then result in the error:  </p>
  
  <blockquote>
    <p>"Attempted to read or write protected memory. This is often an
    indication that other memory is corrupt."</p>
  </blockquote>
  
  <p>There is no inner exception. Inside my <code>Parallel.For</code> loop, I am creating an opening the database connection as local objects. My code looks like this:</p>
  
  <pre><code>static void CheckSinglePath(Path p)
  {    
       string sqlBase = "select * from table where hour = #HOUR#";
       Parallel.For (1, 24, i =&gt;
       {        
              DBManager localdbm = new DBManager();                
              string sql = sqlBase;
              sql = sql.Replace("#HOUR#", i.ToString());
              OracleDataReader reader = db.GetData(sql);
              if (reader.Read())
              {
                 //do some stuff
              }
              reader.Close();
       });
  }
  
  class DBManager
  {
      OracleConnection conn;
      OracleCommand cmd;
      public DBManager()
      {
          string connStr = "blahblahblah;Connection Timeout=600;";
          conn = new OracleConnection(connStr);            
          conn.Open();
          cmd = conn.CreateCommand();
      }
  
      public OracleDataReader GetData(string sql)
      {
          cmd.CommandText = sql;
          return cmd.ExecuteReader();//EXCEPTION HERE!
      }        
  }
  </code></pre>
  
  <p>What am I doing wrong? How can I create 24 parallel Oracle connections to process the data? I'm guessing there is some sort of race condition or memory leak that is going on here which I don't fully understand because it seems to be coming from inside the <code>OracleConnection</code> object. Is the database connection not threadsafe? I tried changing the connection string to use a connection pool and that didn't change anything.</p>