WCF 是否支持在事务范围内异步操作的调用?



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

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

在这种情况下,我假设事务将正常工作,对吗?

我对此表示非常怀疑。如果您正在启动 ascync 操作,您似乎不再参与原始事务。

我写了一个小的 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
    }
}
您需要

在创建的任务中同时设置 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
    }
}

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

最新更新