From: http://www.cnblogs.com/yank/archive/2008/04/01/1132825.html
In lineCodeReuse to reduce variable creation. We hope that the parameters can be reused.
Main Code
// Query the total number of emails in this directory
String Strsum = " Select count (f_id) from DBO. t_tlmail_receiver where f_receiver = @ f_receiver and f_dirid = @ f_dirid " ;
// Query the number of unread mails in this directory
String Strunread = " Select count (f_id) from DBO. t_tlmail_receiver where f_receiver = @ f_receiver and f_state = 0 and f_dirid = @ f_dirid " ;
Sqlparameter [] Params = {
New Sqlparameter ( " @ F_receiver " , Sqldbtype. INT ),
New Sqlparameter ( " @ F_dirid " , Sqldbtype. INT )} ;
Int Unread, total;
Datarow row = Null ;
Foreach (Keyvaluepair < Int , String > Item In Dirs)
{
Params [ 0 ]. Value = Userid;
Params [ 1 ]. Value = Item. Key;
Total = Datahelper. sqlhelper. getcount (strsum, Params, connection );
If (Total > 0 )
{
Params [ 0 ]. Value = Userid;
Params [ 1 ]. Value = Item. Key;
Unread = Datahelper. sqlhelper. getcount (strunread, Params, connection );
}
Row = Ntable. newrow ();
Row [ " F_id " ] = Item. Key;
Row [ " F_directory " ] = Item. value;
Row [ " F_unreadcount " ] = Unread;
Row [ " F_totalcount " ] = Total;
Ntable. Rows. Add (ROW );
}
The error is as follows: : Another sqlparametercollection already contains sqlparameter .
Error details : System. argumentexception: Another sqlparametercollection contains sqlparameter .
Specific reasons: The declared sqlparameter array. in the loop, each executenonquery execution is performed by the idbcommand. Parameters. Add (idbdataparameter) inside the method to add the sqlparameter array to the idataparametercollection of idbcommand. The Framework mechanism limits two idataparametercollection objects to point to the same object. Although the executenonquery method declares a temporary idbcommand object, theoretically, this idbcommand object containing the idataparametercollection will be released from the memory at the end of the executenonquery method. However, it may be because the garbage collection mechanism does not immediately recycle the temporary idbcommand object, and the parameter set bound to the object also exists, just like adding an item to a dropdownlist. In this case, two idataparametercollection objects point to the same object during the next loop.
Solution 1 : Re-generate an object during each loop, but this will generate a large number of junk variables, which are not desirable.
Solution 2: Clear the parameters set of Command commands after use.Preparecommand (CMD, Con, plain text, plain parms );
Count = BMC. clutility. getconvertintvalue (CMD. executescalar ());
Cmd. Parameters. Clear ();