1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- using System;
- using System.Data;
- using System.Data.SqlClient;
- using System.Diagnostics;
- namespace LJLib.SQLEX
- {
- public sealed class LJTransactionScope : IDisposable
- {
- private bool complete = false;
- private bool ifCreateTran = false;
- private SqlCommand _cmd;
- private string pointName;
- public LJTransactionScope(SqlCommand cmd)
- {
- Trace.Assert(cmd != null && cmd.Connection.State == ConnectionState.Open, "cmd != null && cmd.Connection.State == ConnectionState.Open");
- pointName = Guid.NewGuid().ToString("N");
- _cmd = cmd;
- if (_cmd == null) return;
- if (_cmd.Transaction == null)
- {
- _cmd.Transaction = _cmd.Connection.BeginTransaction(IsolationLevel.ReadUncommitted);
- ifCreateTran = true;
- }
- _cmd.Transaction.Save(pointName);
- }
- public void Complete()
- {
- if (_cmd != null && ifCreateTran)
- {
- _cmd.Transaction.Commit();
- }
- complete = true;
- }
- public void Dispose()
- {
- if (_cmd == null) return;
- if (!complete)
- {
- try
- {
- _cmd.Transaction.Rollback(pointName);
- if (ifCreateTran)
- {
- _cmd.Transaction.Rollback();
- }
- }
- catch (Exception ex)
- {
- Trace.Write(ex);
- }
- }
- if (ifCreateTran)
- {
- using (_cmd.Transaction) { }
- _cmd.Transaction = null;
- }
- }
- }
- }
|