开发者

Can we implement Transaction on C# objects?

开发者 https://www.devze.com 2022-12-21 09:27 出处:网络
Can we use transaction on C# objects. Does all the Transactions are only for 开发者_Go百科Relational Database like MSSQL, ORACLE, etc...??

Can we use transaction on C# objects.

Does all the Transactions are only for 开发者_Go百科Relational Database like MSSQL, ORACLE, etc...??

Thanks.


What you are asking is called Software Transactional Memory. Since this is currently an open area of research and there is no native C# language support at the moment, you might be better off using the existing synchronization options for C#, such as the lock keyword, monitors, wait handles, etc.

If you really need advanced transactional features, there are a lot of library implementations, see this list in Wikipedia for some examples:

  • https://en.wikipedia.org/wiki/Software_transactional_memory#C.23


You may be interested by Software Transactional Memory. It exists one implementation in the .NET world, named STM.NET.

Software Transactional Memory (STM.NET) is a mechanism for efficient isolation of shared state. The programmer demarcates a region of code as operating within a transaction that is "atomic" and "isolated" from other transacted code running concurrently.

Here is the blog of the Microsoft STM.NET team : http://blogs.msdn.com/stmteam/


For a nice discussion how to implement transaction in OOP take a look at this discussion. There the memento and state pattern are highlighted to achieve transactional behaviour (among other methods).


Have a look at Software Transactional Memory (STM.NET).

It didn't make it into .Net 4 but is available as a separate download


There was an Interesting article on Joe Duffy's blog about the attempt to do Transactional Memory at MS. If I were to sum it up, I would say: Only do this yourself if it is for fun.


It looks like Microsoft has moved away from stm. Some of the reasoning is given here https://www.infoq.com/news/2010/05/STM-Dropped although i am not fully sold on its weaky atomic in place modification argument. I think a strongly atomic transaction where all the objects state must lie inside a transaction still has merit.


There is no SQL-like transactioning for c# objects, but if this because you have threading problems, you should use lock:

lock (myList)
{
    if (myList.Count > 0)
        myList.Clear();
}

This simply clears a list but ensures it can't be modified by another thread at the same time.


You can use the TransactionScope Class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号