The task. Run in a for loop

I have a for loop inside which

First: I want to calculate the SQL required to run

Second: Run SQL asynchronously, without waiting for them to complete in a loop

My code looks like this:

 for ( int i = 0; i < gm.ListGroupMembershipUploadDetailsInput.GroupMembershipUploadInputList.Count; i++) { // Compute SQL.Upload.UploadDetails.insertGroupMembershipRecords( gm.ListGroupMembershipUploadDetailsInput.GroupMembershipUploadInputList[i],max_seq_key++,max_unit_key++, out strSPQuery, out listParam); //Run the out SPQuery async Task.Run(() => rep.ExecuteStoredProcedureInputTypeAsync(strSPQuery, listParam)); } 

The insertGroupMembershipRecords method in a separate DAL class looks like this:

 public static GroupMembershipUploadInput insertGroupMembershipRecords(GroupMembershipUploadInput gm, List<ChapterUploadFileDetailsHelper> ch, long max_seq_key, long max_unit_key, out string strSPQuery, out List<object> parameters) { GroupMembershipUploadInput gmHelper = new GroupMembershipUploadInput(); gmHelper = gm; int com_unit_key = -1; foreach(var item in com_unit_key_lst){ if (item.nk_ecode == gm.nk_ecode) com_unit_key = item.unit_key; } int intNumberOfInputParameters = 42; List<string> listOutputParameters = new List<string> { "o_outputMessage" }; strSPQuery = SPHelper.createSPQuery("dw_stuart_macs.strx_inst_cnst_grp_mbrshp", intNumberOfInputParameters, listOutputParameters); var ParamObjects = new List<object>(); ParamObjects.Add(SPHelper.createTdParameter("i_seq_key", max_seq_key, "IN", TdType.BigInt, 10)); ParamObjects.Add(SPHelper.createTdParameter("i_chpt_cd", "S" + gm.appl_src_cd.Substring(1), "IN", TdType.VarChar, 4)); ParamObjects.Add(SPHelper.createTdParameter("i_nk_ecode", gm.nk_ecode, "IN", TdType.Char, 5)); // rest of the method } 

But in the case of a list Count of 2k that I tried,

He did not insert 2k records into the database, but only 1.

Why does this not insert all the entries that the input list has?

What am I missing?

+5
source share
1 answer

Task. Run in a for loop

Despite the fact that this is not a question, the title itself is what I am going to solve. For CPU-bound operations, you can use Parallel.For or Parallel.ForEach , but since we are bound to IO (i.e. Database Calls), we need to rethink this approach.

The obvious answer here is to create a list of tasks representing asynchronous operations, and then wait for them using the Task.WhenAll API, like this:

 public async Task InvokeAllTheSqlAsync() { var list = gm.ListGroupMembershipUploadDetailsInput.GroupMembershipUploadInputList; var tasks = Enumerable.Range(0, list.Count).Select(i => { var value = list[i]; string strSPQuery; List<SqlParameter> listParam; SQL.Upload.UploadDetails.insertGroupMembershipRecords( value, max_seq_key++, max_unit_key++, out strSPQuery, out listParam ); return rep.ExecuteStoredProcedureInputTypeAsync(strSPQuery, listParam); }); await Task.WhenAll(tasks); } 
+3
source

All Articles