【问题标题】:Async Consumer and use of TransactionScope异步消费者和 TransactionScope 的使用
【发布时间】:2013-04-04 03:25:15
【问题描述】:

我正在使用IBM.XMS lib 与 WebSphereMQ 通信。

当使用同步方式接收消息时,例如:

using (var scope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
{
       message = consumer.Receive(1000);

       if (message != null)
       {
            //Do work here
            scope.Complete();
       }
}

但是如果我想使用异步方法:

consumer.MessageListener = delegate(IMessage msg)
{
    //Do work here
    //But where do I put TransactionScope?
};

我不知道如何将MessageListener 回调封装在TransactionScope 中。

有人知道怎么做吗?

【问题讨论】:

  • 如果消费者实例是从会话创建的,那么会话可能已经创建,因此在委托运行期间 (Transaction.Current) 周围存在环境事务。

标签: c# ibm-mq


【解决方案1】:

消息侦听器(又名异步使用者)不能在 TransactionScope 中使用,因为消息侦听器在与创建 TransactionScope 的线程不同的线程上运行。您只能在TransactionScope 中使用同步接收/发送。

link 表示“异步消费者不支持 XA 事务。”

【讨论】:

【解决方案2】:

使用DependentClone 创建DependentTransaction 可能值得您研究。

“从属事务是其结果取决于从中克隆它的事务的结果的事务。”

“DependentTransaction 是使用 DependentClone 方法创建的 Transaction 对象的克隆。它的唯一目的是允许应用程序停止并保证在事务仍在执行工作时事务不能提交(例如, 在工作线程上)。”

编辑:刚刚在相关的 SO 问题列表中发现了这个:related question and answer 查看他们提供的 msdn 链接:非常值得一读 Managing Concurrency with DependentTransaction

取自上面的 MSDN 链接(为简洁起见):

public class WorkerThread
{
    public void DoWork(DependentTransaction dependentTransaction)
    {
        Thread thread = new Thread(ThreadMethod);
        thread.Start(dependentTransaction); 
    }

    public void ThreadMethod(object transaction) 
    { 
        DependentTransaction dependentTransaction = transaction as DependentTransaction;
        Debug.Assert(dependentTransaction != null);

        try
        {
            using(TransactionScope ts = new TransactionScope(dependentTransaction))
            {
                /* Perform transactional work here */ 
                ts.Complete();
            }
        }
        finally
        {
            dependentTransaction.Complete(); 
            dependentTransaction.Dispose(); 
        }
    }

//Client code 
using(TransactionScope scope = new TransactionScope())
{
    Transaction currentTransaction = Transaction.Current;
    DependentTransaction dependentTransaction;    
    dependentTransaction = currentTransaction.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
    WorkerThread workerThread = new WorkerThread();
    workerThread.DoWork(dependentTransaction);

    /* Do some transactional work here, then: */
    scope.Complete();
}

【讨论】:

  • 我需要在TransactionScope 中登记消息的实际出队,我看不出这将如何解决任何问题!
  • 那你为什么不使用 MessageQueueTransaction 呢? msdn.microsoft.com/en-us/library/…
  • MessageQueueTransaction 与MessageQueue、MSMQ 一起使用。我没有使用 MSMQ,我使用的是 WebSphereMQ
  • 啊我的坏...你看过stackoverflow.com/questions/3084849/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 2019-01-20
  • 2016-05-09
  • 2018-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多