如何以及何时在C#中处理对象?
我必须从一个数据库中读取大量Blob数据(超过300Gb),然后插入到另一个数据库中如何以及何时在C#中处理对象?,c#,ado.net,C#,Ado.net,我必须从一个数据库中读取大量Blob数据(超过300Gb),然后插入到另一个数据库中 if (dr.HasRows) { while (dr.Read()) { media m = new media { docid = Convert.ToInt32(dr["Id"]), Content = Convert.ToByte(dr["BlobData"]), madiaName = Con
if (dr.HasRows)
{
while (dr.Read())
{
media m = new media
{
docid = Convert.ToInt32(dr["Id"]),
Content = Convert.ToByte(dr["BlobData"]),
madiaName = Convert.ToString(dr["Name"])
}
}
InsertInNewDb(m);
}
我正在逐行读取数据并在另一个数据库中插入数据。问题是,由于我没有处理对象,所以在发送一些数据后会生成内存已满异常。
如何在一次迭代后处理对象?您可以尝试对DataReader进行分页,这应该可以正常工作。尝试在某些行之后同时关闭连接、数据源和数据目标。请记住,使用带有说明的对象可以更好地管理内存。要将多个答案和注释联系在一起,请尝试以下方法:
// The SqlConnection, SqlCommand and SqlDataReader need to be in using blocks
// so that they are disposed in a timely manner. This does not clean up
// memory, it cleans up unmanaged resources like handles
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM OldTable", conn))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
media m = new media
{
// Don't convert - cast instead. These are already the correct
// type.
docid = (int) dr["Id"],
// There are more efficient ways to do this, but
// Convert.ToByte was copying only a single byte
Content = dr["BlobData"],
madiaName = (string)dr["Name"]
}
// You probably want to insert _all_ of the rows.
// Your code was only inserting the last
InsertInNewDb(m);
}
}
}
}
}
“我必须读取大量Blob数据(超过300Gb)”-呃,wtf!您必须进行缓冲和分块读取…最大的单个.NET对象是2GB。处置不是问题,除非您有300GB的内存,否则无法将那么多内容读入内存。处置对象与内存无关。它与释放非托管资源(如文件句柄)有关。也许给我们实际的代码会有所帮助。给我们一个不代表问题的简单示例意味着我们只能猜测..而且,
m=null代码>在.NET中不可用。这不是VB6。如何将对象与正在使用的语句一起使用?它表明一个类应该是idisposableSorry,我的意思是与连接对象、命令和数据读取器等一起使用。他的对象应该实现IDisPosable,以便与using
block一起使用。。