获取的TransactionScope与异步工作

获取的TransactionScope与异步工作

本文介绍了获取的TransactionScope与异步工作/待机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图整合异步/等待到我们的服务总线。
我实现了基于这个例子http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx.

I'm trying to integrate async / await into our service bus.I implemented a SingleThreadSynchronizationContext based on this example http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx.

和它工作得很好,除了一件事:TransactionScope的。我在等待着为的TransactionScope内的东西,它打破了TransactionScope的。

And it works fine, except for one thing : TransactionScope. I await for stuff inside the TransactionScope and it break the TransactionScope.

的TransactionScope似乎并不玩异步/的await,肯定是因为它店里的东西在线程中使用ThreadStaticAttribute不错。我得到这个异​​常:嵌套TransactionScope的错误。

TransactionScope doesn't seems to play nice with the async / await, certainly because it store things in the thread using ThreadStaticAttribute. I get this exception : "TransactionScope nested incorrectly.".

我试过排队任务之前保存的TransactionScope数据并运行它之前恢复,但它似乎并不改变任何事情。而TransactionScope的code是一个烂摊子,所以真的很难理解这是怎么回事那里。

I tried to save TransactionScope data before queuing the task and restore it before running it but it doesn't seems to change a thing. And TransactionScope code is a mess, so it's really hard to understand what's going on there.

有没有一种方法,使工作?有一些替代的TransactionScope?

Is there a way to make it work ? Is there some alternative to TransactionScope ?

推荐答案

在.NET框架4.5.1,有一组的new为的TransactionScope 构造函数,采取了 TransactionScopeAsyncFlowOption 参数。

In .NET Framework 4.5.1, there is a set of new constructors for TransactionScope that take a TransactionScopeAsyncFlowOption parameter.

根据MSDN的,它可以跨线程延续交易流程。

According to the MSDN, it enables transaction flow across thread continuations.

我的理解是,它的目的是让你写code这样的(我还没有尝试过):

My understanding is that it is meant to allow you to write code like this (I have not tried it yet):

// transaction scope
using (var scope = new TransactionScope(... ,
  TransactionScopeAsyncFlowOption.Enabled))
{
  // connection
  using (var connection = new SqlConnection(_connectionString))
  {
    // open connection asynchronously
    await connection.OpenAsync();

    using (var command = connection.CreateCommand())
    {
      command.CommandText = ...;

      // run command asynchronously
      using (var dataReader = await command.ExecuteReaderAsync())
      {
        while (dataReader.Read())
        {
          ...
        }
      }
    }
  }
  scope.Complete();
}

这篇关于获取的TransactionScope与异步工作/待机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:36