About working with transaction for non-database transactions

Source: Internet
Author: User
Tags try catch

In the process of manipulating the database, for data consistency, we can use transaction, either commit all when it succeeds, or have any one operation fail to roll back immediately. Not only in the database, sometimes operating other content, such as the operation of the system files, but also need to consider some of the operation of the combination of a transaction.

Now let's look at an example like this. Now we need to create 3 directory a,b,c on the computer's hard disk, requiring either 3 to be all created successfully, or not to create one. We can think of this as a matter of affairs. If we write our own code to do this, we can write this.

[CSharp]View Plaincopy
  1. BOOL Createa = false;
  2. BOOL Createb = false;
  3. BOOL Createc = false;
  4. Try
  5. {
  6. //The operation here is to create a 3 directory
  7. Directory.CreateDirectory ("\\a");
  8. Createa = true;
  9. Directory.CreateDirectory ("\\b");
  10. Createb = true;
  11. Directory.CreateDirectory ("\\c");
  12. Createc = true;
  13. }
  14. catch (System.Exception ex)
  15. {
  16. //Here, when catching an exception, roll back according to the result of the run
  17. if (CREATEB)
  18. {
  19. Directory.delete ("\\b");
  20. Directory.delete ("\\a");
  21. }
  22. if (!createb && createa)
  23. {
  24. Directory.delete ("\\a");
  25. }
  26. }



But here we are to roll these 3 operations as a whole, in time it is simple to create a delete folder, we can see the rollback logic in the catch is very complex. As you can imagine, if the 3 steps of a,b,c are more than just creating a directory, and there are some other operations, then the logic of rollback is very complex, and we can consider dividing this one into several small transactions and rolling it back. The code can write this, and here we use the Transactin and Transactioscope classes provided by the framework.

[CSharp]View Plaincopy
  1. Class Program
  2. {
  3. static void Main (string[] args)
  4. {
  5. //Do not need a try catch here, because scope has already completed this function,
  6. //That is, when an exception occurs, it will attempt to jump out of the using code block,
  7. //CLR will call each transaction before running an exception outside of the code block, respectively.
  8. //roolback method, as long as the logic in rollback you define is not a problem, then all
  9. //The actions that have occurred will be safely rolled back.
  10. using (var scope = new TransactionScope ())
  11. {
  12. var A = new Operationa ();
  13. Transaction.Current.EnlistVolatile (A, Enlistmentoptions.none);
  14. A.dowork ();
  15. Operationb B = new Operationb ();
  16. Transaction.Current.EnlistVolatile (B, Enlistmentoptions.none);
  17. B.dowork ();
  18. Scope.complete ();
  19. }
  20. }
  21. }
  22. }
  23. Class Operationa:ienlistmentnotification
  24. {
  25. private bool _iscommitsucceed = false;
  26. public void Commit (Enlistment enlistment)
  27. {
  28. Enlistment. Done ();
  29. }
  30. public void DoWork ()//This is a custom method, not an inheritance ienlistmentnotification
  31. {
  32. Directory.CreateDirectory ("\\a");
  33. //There are some other complex operations on a.
  34. _iscommitsucceed = true;
  35. }
  36. public void InDoubt (Enlistment enlistment)
  37. {
  38. Enlistment. Done ();
  39. }
  40. public void Prepare (preparingenlistment preparingenlistment)
  41. {
  42. Preparingenlistment.prepared ();
  43. }
  44. public void Rollback (Enlistment enlistment)
  45. {
  46. //Roll back some of the operations of a, of course, the operation logic here requires you to write.
  47. //For example, to see if the creation was successful, or to have some other signal markers,
  48. //Tag you decide whether to delete the directory or what other rollback operations.
  49. if (_iscommitsucceed)
  50. Directory.delete ("\\a");
  51. Enlistment. Done ();
  52. }
  53. }
  54. Class Operationb:ienlistmentnotification
  55. {
  56. private bool _iscommitsucceed = false;
  57. public void Commit (Enlistment enlistment)
  58. {
  59. Enlistment. Done ();
  60. }
  61. public void DoWork ()
  62. {
  63. //Here are some of the complex operations on B
  64. throw New Exception ("test");
  65. //There are still some operation code here, but we are simulating that the B operation throws an exception, so the code here does not execute
  66. }
  67. public void InDoubt (Enlistment enlistment)
  68. {
  69. Enlistment. Done ();
  70. }
  71. public void Prepare (preparingenlistment preparingenlistment)
  72. {
  73. Preparingenlistment.prepared ();
  74. }
  75. public void Rollback (Enlistment enlistment)
  76. {
  77. if (_iscommitsucceed)
  78. {
  79. //Roll back some of the already existing operations of B.
  80. }
  81. Enlistment. Done ();
  82. }


The mechanism here is that there may be a special operation in the Scope.complete () method that tells the CLR that all operations have been completed successfully and that there is no need to invoke those transaction rollback methods when jumping out of this scope. If the Scope.complete () method is not executed, then the rollback method is called when you jump out of the scope code block. This is generally caused by an exception in the logical operation of a transaction, causing the exception to be thrown out of this code block from this direct throw, without the opportunity to execute the code below. It can be seen that the focus here is to write rollback logic, but relative to the original catch logic, here separate for a number of small logic, relatively easy a lot.

It's just a personal writing logic that uses rollback. When using ienlistmentnotification, someone also writes the business logic to commit. If you want to really understand the mechanism of transaction rollback, it is recommended to understand the implementation mechanism of TransactionScope and transactiond in depth.

About working with transaction for non-database transactions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.