.net - Creating new transaction scope in a loop performance -
consider
foreach (var myentity in myentities) { using (transactionscope scope = new transactionscope()) { // not important code myentity.imageurl = fixurl(myentity.imageurl); myentity additionalentity = clone(myentity); additionalentity.datecreated = datetime.now; additionalentity.createdby = getcurrentuser(); //step 1 serverdbcontext.update(myentity); //step 2 addtoqueue(myentity); //step 3 anotherserverdbcontext.insert(myentity); scope.complete(); } } notice transactionscope created inside foreach statement. experiment code confirmed transcaction scope expensive operation.
it expected addtoqueue may throw exceptions. in case don't want changes made neither in server1 database, nor in server2 database regarding entity.
without transaction scope code executes in few seconds, while using on execution takes forever. i'm looking still able not change underlying records in case of exception @ of 1,2 or 3 steps.
obviously moving foreach inside of using not enough because if @ least 1 pass of loop fails, records may broken , nothing updated.
what need know more transactioning mechanism or other appraches tried here?
transactionscope expensive because transactions expensive.
if want guarantee of consistency, don't want make entire operation 1 unit of work, may find operation completes faster if parallelise it. simple way achieve use parallel.foreach:
myentities.asparallel().foreach(entity => { using (transactionscope scope = new transactionscope()) { // operation perform in parallel. scope.complete(); } } obviously introduces asynchronous processing, need careful around objects share in concurrently running loop.
if isn't option, other practical alternative give atomic consistency , move system of eventual consistency. in case mean running without scope , performing regular "cleanup" actions undo "bad" records not in consistent state.
Comments
Post a Comment