我正在尝试使用WCF事务实现,我想知道WCF 4.0是否支持异步事务。
例如,我有几个启用客户端\服务事务的服务操作,在客户端,我使用TransactionScope,并在事务内创建任务以异步调用这些操作。
在这种情况下,我假设事务将正常工作,是这样吗?
例如,我有几个启用客户端\服务事务的服务操作,在客户端,我使用TransactionScope,并在事务内创建任务以异步调用这些操作。
在这种情况下,我假设事务将正常工作,是这样吗?
我非常怀疑这一点。如果您启动了一个异步操作,似乎您不再参与原始事务。
我写了一个小的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
}
}
正如你所料,这会变得重复,因此我建议为此编写一个辅助程序。