How to dispose TransactionScope in cancelable async/await?

前端 未结 5 1776

I\'m trying to use the new async/await feature to asynchronously work with a DB. As some of the requests can be lengthy, I want to be able to cancel them. The issue I\'m run

5条回答
  •  难免孤独
    2020-12-24 00:51

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

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

    My understanding is that it is meant to allow you to write code like this:

    // 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();
    }
    

    I have not tried it yet, so I don't know if it will work.

提交回复
热议问题