asp.net - try/catch in TransactionScope in C# -
i'm using transaction in c# code. in transactionscope log make sure done in testing. if happens in transaction , goes catch log class doesn't write anything. in localhost change transactionscopeoption "suppress" because database not in server. when i'm debugging ok, can write log file.but when change "required" if gave error, canceled usual can't write first log. how can fix this?
my code sample:
transactionoptions tr = new transactionoptions(); tr.isolationlevel = system.transactions.isolationlevel.serializable; using (transactionscope scope = new transactionscope(transactionscopeoption.required, tr, system.transactions.enterpriseservicesinteropoption.automatic))//system.timespan.maxvalue)) { bool status = false; // log must written anyway won't when gives error. logprocess log = new logprocess(ssession["dbname"], new guid(), "transaction begun."); try { // process 1 // process 2 . . . if(status) { logprocess log1 = new logprocess(ssession["dbname"], new guid(), "transaction complete soon."); scope.complete(); logprocess log1 = new logprocess(ssession["dbname"], new guid(), "transaction completed."); } else { logprocess log2 = new logprocess(ssession["dbname"], new guid(), "transaction dispose."); scope.dispose(); logprocess log2 = new logprocess(ssession["dbname"], new guid(), "transaction disposed."); } } catch(exception ex) { logprocess log1 = new logprocess(ssession["dbname"], new guid(), "transaction exception. error: " + ex.message); scope.dispose(); } }
first of all, find structure of code sample quite confusing. when using transactionscope, typically don't write statements after scope.complete() or scope.dispose() have been called. moreover, using statement disposes scope you, imho should not call scope.dispose() explicitly if can it. in other words: try refactor code looks this:
private void performtransactionaloperation() { log.write("starting operation."); try { using (var scope = createtransactionscope()) { if (performtransactionaloperationcore()) { log.write("committing..."); scope.complete(); log.write("committed"); } else { log.write("operation aborted."); } } } catch (exception exception) { log.write("operation failed: " + exception.message); throw; } } private bool performtransactionaloperationcore() { // perform operations , return status... }
secondly, transaction-scope designed complete when no exception raised, design might improved letting performtransactionaloperationcore throw specific exception instead of returning false.
then on logging matter: make sure logging framework not participate in same transaction operation logging about. can logging within transactionscope option suppress (that is, when logging resource transaction-aware in first place, database). , way, why writing log-statements instantiating new logprocess-instances?
Comments
Post a Comment