我正在使用数据表从Ldap获取Userdetails到数据库。
处理器内存在执行下面的代码时不断增加,最后我得到“内存异常错误”。
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domainName, userName, passwd, AuthenticationTypes.Secure);
DirectorySearcher dSearch = new DirectorySearcher(entry);
dSearch.PageSize = 1000;
dSearch.Filter = "(objectClass=*)";
dSearch.SearchScope = SearchScope.Subtree;
SearchResultCollection src = dSearch.FindAll();
int i = 0;
DataTable dt = new DataTable();
dt.Columns.Add("mail");
foreach (SearchResult sResultSet in src)
{
DataRow dr = dt.NewRow();
if (GetProperty(sResultSet, "mail") != "")
{
dr["mail"] = GetProperty(sResultSet, "mail").ToString();
}
dt.Rows.Add(dr);
i++;
if (i == 1000)
{
BulkInsertDataTable("TestTable", dt, 2);
dt.Dispose();
dt = new DataTable();
dt.Columns.Add("mail");
i = 0;
}
}
任何人都可以告诉我在每次批量插入数据库后如何释放内存?
先谢谢。
答案 0 :(得分:0)
您的代码仅在索引1000处理一次数据表。从
更改行if (i == 1000)
到
if ((i % 1000) == 0)
// you should also call BulkInsertDataTable("TestTable", dt, 2); after the foreach loop to insert the last set of data as well
答案 1 :(得分:0)
public bool BulkInsertDataTable(string tableName, DataTable dataTable, int Mode)
{
bool isSuccuss = false;
try
{
if (Mode == 2)
{
SqlConnectionObj.Open();
SqlBulkCopy bulkCopy = new SqlBulkCopy(SqlConnectionObj, SqlBulkCopyOptions.TableLock | SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.UseInternalTransaction, null);
bulkCopy.DestinationTableName = tableName;
bulkCopy.WriteToServer(dataTable);
SqlConnectionObj.Close();
isSuccuss = true;
}
}
catch (Exception ex)
{
isSuccuss = false;
throw ex;
}
return isSuccuss;
}