c# - How to optimize and speed up this operation -
list<customer> customers = getcustomers("act"); foreach(var customer in customers) { savecustomerdata (customer); }
now in operation - list of customers object, in thousands save each customer object in database, 1 one. there way speed or make parallel in someway achieve performance , right result.
list<customer> customers = getcustomers("act"); task[] tasks = new task[maxnumofconcurrentsaves]; while(customers.length > 0) { for(int = 0; < maxnumofconcurrenttasks; i++){ tasks[i] = savecustomerdata(customers[i]); customers[i] = null; } customers = list.findall<customer>(customers, acust => !(acust == null)); task.awaitall(tasks) }
ok here's whats happening (and you'll have perfect uses): while have customers in list, every 1 of them starting @ begining through max number of concurrent tasks, start task save , set customer null. then, after loop over, find customer entries in list aren't null , keep them , await tasks complete. if there's nothing left in list loop on , save process complete. savecustomerdata return task executes actual save code.
if 1 sees issues code please edit or bring attention. have not tested in capacity similar i've done works.
edit:
i have found amazing task in .net 4.5 (maybe 4 too, not sure)
list<customer> customers = getcustomers("act"); parallel.foreach(customers, (currentcustomer) => savecustomerdata(currentcustomer))
same thing, multithreaded in 1 line.
Comments
Post a Comment