我正在尝试创建一个system.enterpriseservices.servicedcomponent,以便参与分布式事务。我的主要方法看起来像这样:

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;
    }
}

我要做的是检测分布式交易是否已中止(或回滚),然后再回滚我的更改。例如,我可能已经在磁盘上创建了一个文件,或者做了一些需要撤消的副作用。

我试图处理SystemTransAction.transactionCompletected事件或在dispose()方法中检查了SystemTransAction的状态,而没有成功。

我知道这类似于“补偿”而不是“交易”。

我想做的甚至有意义吗?

有帮助吗?

解决方案 2

回答我自己的问题,通过从 System.Transactions.IenlistmentNotification 也是。

其他提示

除非您需要,否则我建议不要以这种方式管理交易。

如果您希望自己的操作投票中止,如果链条中涉及的其他任何操作失败,或者如果一切顺利,则投票;只是放一个 [AutoComplete] attribute(见 评论 部分 文章)就在您方法的声明上方。

以这种方式,当前交易将被中止,以防万一例外增加,否则将自动完成。

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

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;
        }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top