title: Available Memory for a process
body: <p>I am trying to get the available memory in a process to ensure I do not get an OutOfMemoryException.  I have searched the internet and found several examples of how to get memory <em>used</em> but not <em>available</em>.</p>
  
  <p>Let me provide the use case...</p>
  
  <p>I have a process that is doing a Bulk Insert (using SqlBulkCopy).  I am passing a <code>DataTable</code> into the <code>WriteToServer</code> method.  I cannot use a <code>DataReader</code> because I have to be able to retry the process upon failure.  My first thought was to pick an arbitrary number of rows to insert at a time, say 50,000.  But this is a generic process that does not know the data; it does not know the number of columns nor the amount of data in each row.  So I was thinking I could monitor the memory as I am adding rows to the <code>DataTable</code> and then post it to the <code>SqlBulkCopy</code> when it got close to running out of memory.  </p>
  
  <p>Is this a valid approach or is there a better way?<br>
  If this is a valid approach, what function would I use to determine the amount of available memory?</p>
  
  <p>Here is my code so far...  The <code>AvailableMemoryIsLow</code> is what I cannot figure out how to determine.</p>
  
  <pre><code>// m_buffer is a read-once cache (implements IDataReader) that pulls 
  // data from an external source as needed so it uses very little memory.
  // My original implementation just used m_buffer as the parameter of 
  // WriteToServer but now I have to add retry logic into the process.
  
  DataTable dataTable = new DataTable(m_tableName);
  foreach (DataField d in m_buffer.GetColumns())
      dataTable.Columns.Add(new DataColumn(d.FieldName, d.FieldType));
  
  while (m_buffer.Read())
  {
      DataRow row = dataTable.NewRow();
      for (int i = 0; i &lt; m_buffer.FieldCount; i++)
          row[i] = m_buffer.GetValue(i);
  
      dataTable.Rows.Add(row);
  
      // How do I determine AvailableMemoryIsLow
      if (rowCount++ &gt;= 50000 || AvailableMemoryIsLow)
      {
          PutDataIntoDatabase(dataTable);
          dataTable.Clear();
          rowCount = 0;
      }
  }
  
  if (dataTable.Rows.Count &gt; 0)
      PutDataIntoDatabase(dataTable);
  </code></pre>