Parallel.For maintain input list order on output list
Posted
by
romeozor
on Stack Overflow
See other posts from Stack Overflow
or by romeozor
Published on 2012-06-30T10:31:39Z
Indexed on
2012/06/30
21:16 UTC
Read the original article
Hit count: 295
I'd like some input on keeping the order of a list during heavy-duty operations that I decided to try to do in a parallel manner to see if it boosts performance. (It did!)
I came up with a solution, but since this was my first attempt at anything parallel, I'd need someone to slap my hands if I did something very stupid.
There's a query that returns a list of card owners, sorted by name, then by date of birth. This needs to be rendered in a table on a web page (ASP.Net WebForms). The original coder decided he would construct the table cell-by-cell (TableCell
), add them to rows (TableRow
), then each row to the table. So no GridView, allegedly its performance is bad, but the performance was very poor regardless :).
The database query returns in no time, the most time is spent on looping through the results and adding table cells etc.
I made the following method to maintain the original order of the list:
private TableRow[] ComposeRows(List<CardHolder> queryResult)
{
int queryElementsCount = queryResult.Count();
// array with the query's size
var rowArray = new TableRow[queryElementsCount];
Parallel.For(0, queryElementsCount, i =>
{
var row = new TableRow();
var cell = new TableCell();
// various operations, including simple ones such as:
cell.Text = queryResult[i].Name;
row.Cells.Add(cell);
// here I'm adding the current item to it's original index
// to maintain order in the output list
rowArray[i] = row;
});
return rowArray;
}
So as you can see, because I'm returning a very different type of data (List<CardHolder> -> TableRow[]
), I can't just simply omit the ordering from the original query to do it after the operations.
Also, I also thought it would be a good idea to Dispose()
the objects at the end of each loop, because the query can return a huge list and letting cell and row objects pile up in the heap could impact performance.(?)
How badly did I do? Does anyone have a better solution in case mine is flawed?
© Stack Overflow or respective owner