那么处理这个并正确处理范围的正确方法是什么?
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew)) { using (var conn = GetConnection()) { string query = @"some query that may contain transaction itself or some SP whith transaction included" using (var command = new sqlCommand(query,conn)) command.ExecuteNonquery(); } } scope.Complete(); } // Exception here解决方法 即使调用了scope.Complete(),scope.dispose()也可能抛出TransactionAborted异常.例如,一些足够聪明的存储过程可以处理异常并使用T-sql TRY / CATCH构造在T-sql脚本中中止事务,而不会向调用者抛出异常.
所以我认为我建议的最安全的方法如下:
try{ using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew)) { try { using (var conn = GetConnection()) { string query = @"some query that may contain transaction itself or some SP whith transaction included" using (var command = new sqlCommand(query,conn)) command.ExecuteNonquery(); } } catch (sqlException ex) { // log sql Exception,if any throw; // re-throw exception } scope.Complete(); }}catch (TransactionAbortedException ex){ // we can get here even if scope.Complete() was called. // log TransactionAborted exception if necessary}
并且不用担心处理TransactionScope. scope.dispose在抛出TransactionAborted异常之前执行清理它所需的任何 *** 作.
总结以上是内存溢出为你收集整理的c# – TransactionScope在处置之前中止了交易全部内容,希望文章能够帮你解决c# – TransactionScope在处置之前中止了交易所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)