Geeks With Blogs
Rahul Anand's Blog If my mind can conceive it, and my heart can believe it, I know I can achieve it.

Today I encountered some weird behavior in .NET Framework.

 

I had written some code like:

 

[CODE]

while (reader.Read())

      {                   

DataRow row = dtSchema.NewRow(); 

// The above line was throwing Out of Memory Exception

for (int i = 0; i < reader.FieldCount; i++)

{

row[i] = reader.GetValue(i);

}

// Some logic which uses this row

}

[/CODE]

 

Since I was not adding this row to the DataTable Rows collection, my assumption was it will not affect the memory allocation of DataTable (dtSchema).

 

But I found that the .NET Framework is trying to reallocate the DataTable whenever you do the NewRow on the DataTable (if .NET thinks this Row can not be accomodated in the current allocation). Ideally .NET Framework should try to reallocate the memory only when you are adding a row to the data table.

 

To fix this problem I modified my code to:

 

[CODE]

DataRow row = dtSchema.NewRow();     

// Create only one row and assign it values, before using, in the loop

 

while (reader.Read())

      {                   

for (int i = 0; i < reader.FieldCount; i++)

{

row[i] = reader.GetValue(i);

}

// Some logic which uses this row

}

[/CODE]

 

Posted on Friday, March 2, 2007 10:24 PM C# , .NET Framework | Back to top


Comments on this post: Unexpected behavior in DataTable.NewRow()

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Rahul Anand | Powered by: GeeksWithBlogs.net