Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transactions for C# objects?

Tags:

Just curious, is there any support for transactions on plain C# objects? Like

using (var transaction = new ObjectTransaction(obj))
{
  try
  {
    obj.Prop1 = value;
    obj.Prop2 = value;
    obj.Recalculate(); // may fire exception
    transaction.Commit(); // now obj is saved
  }
  except
  {
     transaction.Rollback(); // now obj properties are restored
  }
}

Just to make answers more useful ;-) is there anything similar in other languages?

Update on STM: here's what it claims:

atomic {
  x++;
  y--;
  throw;
}

will leave x/y unchanged, including chained methods calls. Looks like what I ask for. At least it's very interesting. I think that's close enough. Also, there're similar things in other languages, for example Haskell STM. Notice I don't say that it should be used for production ;-)

like image 260
queen3 Avatar asked Nov 19 '09 18:11

queen3


2 Answers

Microsoft is working on it. Read about Software Transactional Memory.

  • STM.NET
  • STM.NET Team Blog
  • Channel 9 Video: STM.NET: Who. What. Why.
  • Papers on STM

They use a few different syntaxes:

// For those who like arrows
Atomic.Do(() => { 
    obj.Prop1 = value;
    obj.Prop2 = value;
    obj.Recalculate();
});

// For others who prefer exceptions
try { 
    obj.Prop1 = value;
    obj.Prop2 = value;
    obj.Recalculate();
}
catch (AtomicMarker) {
}

// we may get this in C#:
atomic { 
    obj.Prop1 = value;
    obj.Prop2 = value;
    obj.Recalculate();
}
like image 149
Frank Krueger Avatar answered Sep 27 '22 23:09

Frank Krueger


For what its worth, a full-blown STM is a little ways out, and I would strongly recommend against rolling your own.

Fortunately, you can get the functionality you want by carefully designing your classes. In particular, immutable classes support transaction-like behavior out of the box. Since immutable objects return a new copy of themselves each time a property is set, you always have a full-history changes to rollback on if necessary.

like image 22
Juliet Avatar answered Sep 27 '22 22:09

Juliet