LJTransactionScope.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using System.Diagnostics;
  5. namespace LJLib.SQLEX
  6. {
  7. public sealed class LJTransactionScope : IDisposable
  8. {
  9. private bool complete = false;
  10. private bool ifCreateTran = false;
  11. private SqlCommand _cmd;
  12. private string pointName;
  13. public LJTransactionScope(SqlCommand cmd)
  14. {
  15. Trace.Assert(cmd != null && cmd.Connection.State == ConnectionState.Open, "cmd != null && cmd.Connection.State == ConnectionState.Open");
  16. pointName = Guid.NewGuid().ToString("N");
  17. _cmd = cmd;
  18. if (_cmd == null) return;
  19. if (_cmd.Transaction == null)
  20. {
  21. _cmd.Transaction = _cmd.Connection.BeginTransaction(IsolationLevel.ReadUncommitted);
  22. ifCreateTran = true;
  23. }
  24. _cmd.Transaction.Save(pointName);
  25. }
  26. public void Complete()
  27. {
  28. if (_cmd != null && ifCreateTran)
  29. {
  30. _cmd.Transaction.Commit();
  31. }
  32. complete = true;
  33. }
  34. public void Dispose()
  35. {
  36. if (_cmd == null) return;
  37. if (!complete)
  38. {
  39. try
  40. {
  41. _cmd.Transaction.Rollback(pointName);
  42. if (ifCreateTran)
  43. {
  44. _cmd.Transaction.Rollback();
  45. }
  46. }
  47. catch (Exception ex)
  48. {
  49. Trace.Write(ex);
  50. }
  51. }
  52. if (ifCreateTran)
  53. {
  54. using (_cmd.Transaction) { }
  55. _cmd.Transaction = null;
  56. }
  57. }
  58. }
  59. }