WCF 事务

来源:互联网 发布:订阅股票实时行情数据 编辑:程序博客网 时间:2024/05/16 16:15

1、概念

通过事务可以帮助达到该一致性。一个事务指一个组工作或一系列操作的原子性,原子性意味着要么全部成功地执行,要么当某个异常发生时全部均不执行,在SOA环境中,事务可以跨越多个服务,可能运行在不同组织的不同的计算机上;这就是所谓的分布式事务。在这种环境下,基础架构必须保证跨越网络的一致性和各种数据存贮之间的一致性

2、WCF中实现方式:

WCF运用事务的基本设置包括三项:

a.绑定中添加事务流 transactionFlow=true;

b.操作契约中添加[TransactionFlow(TransactionFlowOption....)]属性;

c.服务类中添加事务环境[OperationBehavior(TransactionAutoComlete=true,TransactionScopeRequired=true)];

d.如果服务类的实例不是 InstanceContextMode.PerCall,则需要在[ServiceBehavior(ReleaseServiceInstanceOnTransactionComplete=false)];

下面是它们的组合,会产生不同的事务传播模式

绑定事务流

TransactionFlowOption

TransactionScopeRequired

事务模式

False

Allowed

False

None

False

Allowed

True

Service

False

NotAllowed

False

None

False

NotAllowed

True

Service

True

Allowed

False

None

True

Allowed

True

Client/Service

True

Mandatory

False

None

True

Mandatory

True

client

Client/Service模式:客户端包含事务时,以客户端的事务为根;如果客户端没有包含事务,则以服务端为事务的根;

Client模式:始终以客户端的事务为根;

Service模式:以服务端的事务为根;

None模式:没有运用到事务;


3、代码:

服务器:

        [OperationBehavior(TransactionScopeRequired=true, TransactionAutoComplete=true)]
        int IServiceClass.MultiplyNumbers(int firstvalue, int secondvalue)
        {
            return firstvalue * secondvalue;
        }

客户端:

        private void button2_Click(object sender, EventArgs e)
        {
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
            {
                TCP.ServiceClassClient client = new
                    WCFClientApp.TCP.ServiceClassClient("NetTcpBinding_IServiceClass");
                textBox2.Text = client.MultiplyNumbers(val1, val2).ToString();
                ts.Complete();
            }                    
        }

原创粉丝点击