c# - Using Parallel.ForEach and Tasks.Factory.StartNew for database insertion/updation -


i working in .net 4.0 , code supposed this:

i have webapi exposed user . in have collection of objects . concurrentbag containing objects . have iterate on each object in collection , insert/update data in database . count of objects can high (200-300) . adding , if there can multiple concurrent users using api .

now , insertion / updation slow each record conn made database makes process slow . unfortunately cant change logic .

to improve performance using parallel.foreach instead of routine foreach each iteration diffrent. also, creating seperate task each insertion in db

here code

 var tasks = new list<task>(allrecordings.count);//creating task list   parallel.foreach(allrecordings, recording =>         {             var recordingitem = recording;             //lines of code              //                                                   if ( conditions){           var task = task.factory.startnew(                                () => saverecordingdetailstodb(ref recordingitem, device.locale));            recording.title = recordingitem.title;            recording.programid =recordingitem.programid;            recording.seriesid = recordingitem.seriesid;            tasks.add(task);//adding task list            }          });          task.waitall(tasks.toarray()); //waiting tasks complete before going main                                              function } 

can memoryleak occur in above block when there multiple concurrent requests consuming same api also, using parallel.foreach better here normal foreach.

the tpl (task parallel library) designed compute-bound operations, operations can completed in parallel (like calculations on different cpu cores). in case, write database, so, write file system, i.e. io operation. io operations cannot executed in parallel in sense of pure parallelism. if run several io operations simultaneously, interrupt each other , take more time complete comparing running them 1 one. of course, database server should somehow handle situation, not faster sending requests 1 one, more likely, slower.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -