You can break your query up into smaller chunks using the ROW_NUMBER
function in SQL Server to paginate your results.
I've based the answer in this question:
Paginate rows from SQL
First you have to convert your query to one that performs pagination:
string sql = @"SELECT
*
FROM
(
SELECT
ROW_NUMBER() OVER(ORDER BY Id DESC) AS RowNumber,
*
FROM
PhotoStorages
) AS T
WHERE
RowNumber BETWEEN @start AND @start + @pageSize";
You should change the ORDER BY Id
to match the actual ID column of your query. In your specific case, you can use any column in your table since you are using all data, you don't need to worry about the order being returned. 5000 rows is not big in the grand scheme of things but if it was a large table 100,000+ rows, you will want to use a column that has an index on it. And DO NOT use the binary data column.
Then you can run your query inside a loop:
var pageSize = 10;
var startAt = 0;
while(true)
{
using (SqlCommand sqlCommand = new SqlCommand(sql))
{
sqlCommand.Parameters.Add("@start", SqlDbType.Int).Value = startAt;
sqlCommand.Parameters.Add("@pageSize", SqlDbType.Int).Value = pageSize;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand))
{
using (DataTable dataTable = new DataTable())
{
dataAdapter.Fill(dataTable);
var rowCount = dataTable.Rows.Count;
var startAt = startAt + rowCount;
if (dataTable.Rows.Count > 0)
{
for (int i = 0; i < dataTable.Rows.Count; i++)
{
/*Resize the image and again update those resized image to the same database table*/
}
}
else
{
break;
}
}
}
}
}
The idea is to select a certain number of rows (which we have provided via the pageSize
variable. We then take those rows do the resize, and continue the loop. The loop will continue until the query returns no rows. The value you use for pageSize
is up to you, but as an example if you have 2GB of memory free, and each photo is 2MB, you will very roughly be using all memory if your pageSize is 1000 rows. You want to use substantially less than all available memory as this will not only slow down this process, but all other processes happening on the machine that require free memory.
My C# skills are very rusty, but hopefully that should work for you.