Skip to content

Instantly share code, notes, and snippets.

@azborgonovo
Created March 10, 2016 15:09
Show Gist options
  • Save azborgonovo/8e5c7a7337d592744bac to your computer and use it in GitHub Desktop.
Save azborgonovo/8e5c7a7337d592744bac to your computer and use it in GitHub Desktop.
Transactional code with a Volatile Resource Manager
// 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