Created
March 10, 2016 15:09
-
-
Save azborgonovo/8e5c7a7337d592744bac to your computer and use it in GitHub Desktop.
Transactional code with a Volatile Resource Manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://www.codeguru.com/csharp/.net/net_data/sortinganditerating/article.php/c10993/SystemTransactions-Implement-Your-Own-Resource-Manager.htm | |
// https://msdn.microsoft.com/en-us/library/ms229975(v=vs.85).aspx | |
public class VolatileRM : IEnlistmentNotification | |
{ | |
private int memberValue = 0; | |
private int oldMemberValue = 0; | |
public int MemberValue | |
{ | |
get { return memberValue; } | |
} | |
public void SetMemberValue(int newMemberValue) | |
{ | |
Transaction currentTx = Transaction.Current; | |
if (currentTx != null) | |
{ | |
Console.WriteLine("VolatileRM: SetMemberValue - EnlistVolatile"); | |
currentTx.EnlistVolatile(this, EnlistmentOptions.None); | |
} | |
oldMemberValue = memberValue; | |
memberValue = newMemberValue; | |
} | |
#region IEnlistmentNotification Members | |
public void Commit(Enlistment enlistment) | |
{ | |
Console.WriteLine("VolatileRM: Commit"); | |
// Clear out oldMemberValue | |
oldMemberValue = 0; | |
} | |
public void InDoubt(Enlistment enlistment) | |
{ | |
Console.WriteLine("VolatileRM: InDoubt"); | |
} | |
public void Prepare(PreparingEnlistment preparingEnlistment) | |
{ | |
Console.WriteLine("VolatileRM: Prepare"); | |
preparingEnlistment.Prepared(); | |
} | |
public void Rollback(Enlistment enlistment) | |
{ | |
Console.WriteLine("VolatileRM: Rollback"); | |
// Restore previous state | |
memberValue = oldMemberValue; | |
oldMemberValue = 0; | |
} | |
#endregion | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var value = new VolatileRM(); | |
value.SetMemberValue(5); | |
using (var scope = new TransactionScope()) | |
{ | |
value.SetMemberValue(10); | |
scope.Complete(); | |
} | |
Console.WriteLine("Member value: " + value.MemberValue.ToString()); // Value changed to 10 | |
using (var scope = new TransactionScope()) | |
{ | |
value.SetMemberValue(20); | |
} | |
Console.WriteLine("Member value: " + value.MemberValue.ToString()); // Value continues 10, since the transaction wasn't completed | |
Console.ReadLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment