【问题标题】:Do WCF support Asynchronously operations' invoke within TransactionScope?WCF 是否支持在 TransactionScope 内调用异步操作?
【发布时间】:2012-06-05 01:45:43
【问题描述】:

我正在尝试 WCF 事务的实现,我想出了 WCF 4.0 是否支持异步事务的想法。

例如, 我有几个启用了客户端\服务事务的服务操作,在客户端,我使用 TransactionScope,在事务中,我创建任务来异步调用这些操作。

在这种情况下,我假设交易会正常工作,对吗?

【问题讨论】:

    标签: wcf asynchronous transactionscope


    【解决方案1】:

    我非常怀疑这一点。如果您开始异步操作,您似乎不再参与原始事务。

    我写了一个小 LINQPad 测试

    void Main()
    {
        using (var scope = new TransactionScope(TransactionScopeOption.Required))
        {
        try
        {
            Transaction.Current.Dump("created");
            Task.Factory.StartNew(Test);
            scope.Complete();
        }
        catch (Exception e)
        {
        Console.WriteLine(e);
        }
        Thread.Sleep(1000);
    }
    
    Console.WriteLine("closed");
    Thread.Sleep(5000);
    }
    
    
    public void Test()
    {
    using (var scope = new TransactionScope(TransactionScopeOption.Required))
        {
        Transaction.Current.Dump("test start"); // null
        Thread.Sleep(5000);
        Console.WriteLine("done");
        Transaction.Current.Dump("test end"); // null
        }
    }
    

    【讨论】:

    • 查看我的答案以获得解决方案。
    【解决方案2】:

    您需要在创建的任务中同时设置 OperationContext 和 Transaction.Current。

    更具体地说,在服务中您需要这样做:

    public Task ServiceMethod() {
        OperationContext context = OperationContext.Current;
        Transaction transaction = Transaction.Current;
    
        return Task.Factory.StartNew(() => {
             OperationContext.Current = context;
             Transaction.Current = transaction;
    
             // your code, doing awesome stuff
        }
    }
    

    正如您可能怀疑的那样,这会变得重复,所以我建议为它编写一个帮助程序。

    【讨论】:

      猜你喜欢
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 2021-03-07
      • 1970-01-01
      • 2017-12-09
      相关资源
      最近更新 更多