首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ServicedComponent中检测事务中止?

如何在ServicedComponent中检测事务中止?
EN

Stack Overflow用户
提问于 2010-12-11 06:34:16
回答 2查看 387关注 0票数 1

我正在尝试创建一个System.EnterpriseServices.ServicedComponent,以便参与分布式事务。我的main方法看起来像这样:

代码语言:javascript
复制
public void DoSomething()
{
    try
    {
      // do something useful

      // vote for commit

      if (ContextUtil.IsInTransaction)
          ContextUtil.MyTransactionVote = TransactionVote.Commit;
    }

    catch
    {
      // or shoud I use ContextUtil.SetAbort() instead?

      if (ContextUtil.IsInTransaction)
          ContextUtil.MyTransactionVote = TransactionVote.Abort;

      throw;
    }
}

我尝试做的是检测分布式事务是否已中止(或回滚),然后继续回滚我的更改。例如,我可能在磁盘上创建了一个文件,或者做了一些需要撤销的副作用。

我尝试过在Dispose()方法中处理SystemTransaction.TransactionCompleted事件或检查SystemTransaction的状态,但没有成功。

我理解这是类似于“补偿”而不是“交易”。

我想做的事有意义吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-02-28 21:33:33

回答我自己的问题时,这也可以通过从System.Transactions.IEnlistmentNotification派生ServicedComponent来实现。

票数 0
EN

Stack Overflow用户

发布于 2012-02-11 07:49:53

我建议不要以这种方式管理事务,除非您需要它。

如果您希望您的操作在链中涉及的任何其他操作失败时投票中止,或者如果一切正常则投票支持提交;只需将[AutoComplete]属性(请参阅此article中的注释部分)放在方法声明的上方。

这样,当前事务将在异常引发的情况下中止,否则将自动完成。

考虑下面的代码(这可能是一个典型的服务组件类):

代码语言:javascript
复制
using System.EnterpriseServices;

// Description of this serviced component
[Description("This is dummy serviced component")]
public MyServicedComponent : ServicedComponent, IMyServiceProvider
{
    [AutoComplete]
    public DoSomething()
    {
        try {
            OtherServicedComponent component = new OtherServicedComponent()
            component.DoSomethingElse();

            // All the other invocations involved in the current transaction
            // went fine... let's servicedcomponet vote for commit automatically
            // due to [AutoComplete] attribute
        }
        catch (Exception e)
        {
            // Log the failure and let the exception go
            throw e;
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4413907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档